Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which Is Faster $variable[] or array_push($variable, $newValue)? [duplicate]

Which is faster when adding variables to an array?

  1. $variable[] = $newValue;
  2. array_push($variable,$newValue);

and please mention the difference between the two if any.

like image 496
Raj Avatar asked Dec 03 '10 10:12

Raj


1 Answers

http://www.php.net/manual/en/function.array-push.php#53289

Empy bracket doesn't check if a variable is an array first as array_push does. If array_push finds that a variable isn't an array it prints a Warning message if E_ALL error reporting is on.

So array_push is safer than [], until further this is changed by the PHP developers.

$variable[] seems to be a lot faster:

http://www.php.net/manual/en/function.array-push.php#83388

However if you're adding multiple values per iteration array_push() is faster:

http://www.php.net/manual/en/function.array-push.php#84959

But please remember that pre-optimization is the root of all evil. Use whatever you feel more comfortable with, and when you have a performance issue, use a profiler and do some benchmarking.

like image 125
Luca Matteis Avatar answered Oct 10 '22 09:10

Luca Matteis