ZF-5431: using "$arr[] = $var" instead of "array_push($arr, $var)"

Description

Comments

bechmark:


echo '"array_push($arr, $var)" vs. "$arr[] = $var" (add 1 var)'."\n";
$max = 100000;
$var = true;

echo ' array_push($arr, $var): ';
$arr = array();
$start = microtime(true);
for ($i=0; $i<$max; $i++) {
    array_push($arr, $var);
}
$end = microtime(true);
echo ($end-$start)."\n";

echo ' $arr[] = $var         : ';
$arr = array();
$start = microtime(true);
for ($i=0; $i<$max; $i++) {
    $arr[] = $var;
}
$end = microtime(true);
echo ($end-$start)."\n";
echo "--------------------------------\n";



echo '"array_push($arr, $var)" vs. "$arr[] = $var" (add 10 vars)'."\n";
$max = 100000;
$var = true;

echo ' array_push($arr, $var): ';
$arr = array();
$start = microtime(true);
for ($i=0; $i<$max; $i++) {
    array_push($arr, $var, $var, $var, $var, $var, $var, $var, $var, $var, $var);
}
$end = microtime(true);
echo ($end-$start)."\n";

echo ' $arr[] = $var         : ';
$arr = array();
$start = microtime(true);
for ($i=0; $i<$max; $i++) {
    $arr[] = $var; $arr[] = $var; $arr[] = $var; $arr[] = $var; $arr[] = $var;
    $arr[] = $var; $arr[] = $var; $arr[] = $var; $arr[] = $var; $arr[] = $var;
}
$end = microtime(true);
echo ($end-$start)."\n";

output:


"array_push($arr, $var)" vs. "$arr[] = $var" (add 1 var)
 array_push($arr, $var): 0.0417320728302
 $arr[] = $var         : 0.021378993988
--------------------------------
"array_push($arr, $var)" vs. "$arr[] = $var" (add 10 vars)
 array_push($arr, $var): 0.147557020187
 $arr[] = $var         : 0.155264139175

Whats the issue here? The usage of one or the other has always been a negligible difference. Please add more commentary as to what you are advocating.

to add one element to an array the function is twice as slowly as the operator.

This is not a performance issue. The performance difference between [] and array_push is negligible at best and both methods are valid for different reasons.

Bracket notation is useful for adding values to a variable (whether it has been initialized as an array or not). $i = null; $i[] = 'foo'; will not throw a notice, where as array_push($i, 'foo') will throw a E_WARN that the first argument must be an array.

Also, array_push() will return the count of all the elements which in some situations might be useful. Ultimately, its up to the component developer which method better suites the needs of the component.