Both are not equivalent, array_push
adds an item, and $meu_array[0] = 50;
would edit an existing item or create an index at zero.
The equivalent of array_push
is []
without the index, thus:
$meu_array[] = 50;
However array_push has a difference
What sets array_push
from []
is that with it you can add multiple items, like this:
array_push($meu_array, 50, 60, 100, 9, 'a');
Whether it would be equivalent to:
$meu_array[] = 50;
$meu_array[] = 60;
$meu_array[] = 100;
$meu_array[] = 9;
$meu_array[] = 'a';
So in this case it might be more interesting to use array_push
Performance between []
and array_push
Supposedly, the use of []
is a bit better (it's relative), but it's probably micro-optimization, that is, the difference is insignificant, but to write I think it's simpler to use []
than array_push
and besides simple you write less:
$meu_array[] = 50;
array_push($meu_array, 50);
To compare performance you can use the phplegends / tests library, requires composer
the ideal test is to make it into a large array, so just to test $minha_array = range(0, 10000);
this should suffice.
would look like this:
<?php
use PHPLegends\Tests\Bench;
use PHPLegends\Tests\BenchObject;
require 'vendor/autoload.php'; //Composer autoload
$minha_array1 = range(0, 10000);
$minha_array2 = range(0, 10000);
$bench = new Bench;
$bench->defaultCicles(9999); //9999 execuções
$test1 = $bench->addTest(function () use (&$minha_array1) {
$minha_array1[] = 50;
});
$test2 = $bench->addTest(function () use (&$minha_array2) {
array_push($minha_array2, 50);
});
$bench->run();
echo 'Test #1 (time): ', $test1->time(), PHP_EOL;
echo 'Test #2 (time): ', $test2->time(), PHP_EOL;
Result in PHP5.4:
Test #1 (time): 0.041198015213013
Test #2 (time): 0.051141023635864
Result in PHP7.2:
Test #1 (time): 0.0042929649353027
Test #2 (time): 0.0053369998931885
The difference in PHP7.2 seems insignificant, in other versions of PHP the result may be quite different, as in PHP5.4, or even vary between operating systems such as Windows and Linux
In any case, this is micro-optimization and generally we do not have to worry, except if you actually do thousands of executions, but for all other cases use whatever you like best. >
Now multiple additions:
...
$test1 = $bench->addTest(function () use (&$minha_array1) {
$minha_array1[] = 50;
$minha_array1[] = 60;
$minha_array1[] = 100;
$minha_array1[] = 9;
$minha_array1[] = 'a';
});
$test2 = $bench->addTest(function () use (&$minha_array2) {
array_push($minha_array2, 50, 60, 100, 9, 'a');
});
...
Result in PHP5.4:
Test #1 (time): 0.053055047988892
Test #2 (time): 0.056273937225342
Result in PHP7.2:
Test #1 (time): 0.0079491138458252
Test #2 (time): 0.0065710544586182
Note that multiple inserts were slightly better using array_push
, however the difference is minimal, in all tests, for 9999 repetitions is that it seems to be better, but probably the result varies a lot, ie there is no reason to worry about one another.