Member-only story
Boost Your PHP Performance: A General Overview of Faster Function Alternatives (Part 4/4)
Not a Medium member yet? Click here to access this article for FREE!
In the third part of this series, we covered some of the native functions in PHP 8+, comparing their slower and faster alternatives. If you haven’t read it yet, check it out here:
Now, we will finish this series with next functions performance and small benchmarking script for testing.
Performance Comparisons
Below are function comparisons with an explanation of which is faster and why.
1. mt_rand()
vs. random_int()
Comparison: mt_rand()
is faster but less secure, whereas random_int()
uses cryptographic randomness, making it more secure for sensitive applications.
Example:
echo mt_rand(1, 100); // Fast but not cryptographically secure
echo random_int(1, 100); // Slower but cryptographically secure
2. htmlentities()
vs. htmlspecialchars()
Comparison: htmlspecialchars()
only converts special characters (<
, >
, "
, &
), whereas htmlentities()
converts all applicable HTML entities, making it slower but more comprehensive.
Example:
echo htmlspecialchars("<b>Bold</b>"); // "<b>Bold</b>"
echo htmlentities("© 2024"); // "© 2024"
3. array_walk()
vs. foreach
Comparison: array_walk()
is a built-in function that can be slower due to function call overhead, while foreach
is generally faster and more readable.
Example:
$array = [1, 2, 3];
array_walk($array, fn(&$value) => $value *= 2);
foreach ($array as &$value) {
$value *= 2;
}