Speed Test: array_push vs $array[]


/ Published in: PHP
Save to your folder(s)

Took 0.164692 seconds for array[]
Took 0.395778 seconds for array_push

As you can see array_push is more than twice as slow. Here are the reasons. Array_push is a function call, Function calls are always slower. Array_push takes mixed parameters, parameter checking is always slower. Also array[] just looks cleaner and is less to type.

Tips: Always pre-intialize your variables and don't use mixed types even though you can.


Copy this code and paste it in your HTML
  1. $time_start = microtime(true);
  2.  
  3. $myArray = array();
  4.  
  5. for ( $i = 0; $i < 100000; ++$i )
  6. {
  7. $myArray[] = $i;
  8. $myArray[] = 'test a string';
  9. }
  10.  
  11. $time_end = microtime(true);
  12. printf("Took %f seconds for array[]\n", $time_end - $time_start);
  13.  
  14. $time_start = microtime(true);
  15.  
  16. $myArray = array();
  17.  
  18. for ( $i = 0; $i < 100000; ++$i )
  19. {
  20. array_push($myArray, $i);
  21. array_push($myArray, 'test a string');
  22. }
  23.  
  24. $time_end = microtime(true);
  25. printf("Took %f seconds for array_push\n", $time_end - $time_start);

URL: http://www.mthorn.net

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.