Member-only story

Boost Your PHP Performance: A General Overview of Faster Function Alternatives (Part 4/4)

Roman Huliak
4 min readMar 22, 2025

Not a Medium member yet? Click here to access this article for FREE!

Photo by Agê Barros on Unsplash

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>"); // "&lt;b&gt;Bold&lt;/b&gt;"
echo htmlentities("© 2024"); // "&copy; 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;
}

4. strtotime() vs. DateTime::createFromFormat()

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Roman Huliak
Roman Huliak

Written by Roman Huliak

Full Stack Developer with 15 years of experience in ERP systems, skilled in leadership, analysis, and end-to-end development.

Responses (1)

Write a response

Nice article, thanks :)
Regarding #7, you can just do if($array) to check if there are any items in it, which should be faster than empty() as well.

7