Is $array[] Really Faster Than array_push() in PHP?

Susan Sarandon
Release: 2024-11-06 07:55:02
Original
847 people have browsed it

Is $array[] Really Faster Than array_push() in PHP?

Comparing the Speed of $array[] and array_push() in PHP

When it comes to appending elements to an array in PHP, there are two common approaches: using $array[] or array_push(). While the PHP manual recommends avoiding functions for performance reasons, certain arguments suggest that $array[] is slower than array_push(). To clarify this issue, let's delve into the debate with some benchmarks.

Benchmark Results

To determine the speed difference between these two methods, the following code was executed:

<code class="php">$t = microtime(true);
$array = array();
for($i = 0; $i < 10000; $i++) {
    $array[] = $i;
}
print microtime(true) - $t;
print '<br>';
$t = microtime(true);
$array = array();
for($i = 0; $i < 10000; $i++) {
    array_push($array, $i);
}
print microtime(true) - $t;</code>
Copy after login

The results consistently showed that $array[] is approximately 50% faster than array_push().

PHP Manual Insight

The PHP manual explains that using $array[] avoids the overhead of calling a function for single element additions. Surprisingly, even when adding multiple elements, individual $array[] calls proved to be faster than a single array_push() call.

Conclusion

Contrary to some arguments, $array[] is demonstrably faster than array_push() for both single and multiple element additions. While both methods are suitable for different scenarios, $array[] should be considered when speed is a priority.

The above is the detailed content of Is $array[] Really Faster Than array_push() in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!