Posted By

mthorn on 08/09/06


Tagged

php array speedtest


Versions (?)

Speed Test: array_push vs $array[]


 / Published in: PHP
 

URL: http://www.mthorn.net

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

As you can see arraypush is more than twice as slow. Here are the reasons. Arraypush 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.

  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);

Report this snippet  

You need to login to post a comment.