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>
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!