Array vs Obj iteration - PHP Online

Form of PHP Sandbox

Enter Your PHP code here for testing/debugging in the Online PHP Sandbox. As in the usual PHP files, you can also add HTML, but do not forget to add the tag <?php in the places where the PHP script should be executed.



Your result can be seen below.

Result of php executing





Full code of Array vs Obj iteration.php

  1. <?php
  2. $hashes = array();
  3. for ($x=0;$x<100000;$x++) {
  4.     $hashes[] = sha1(rand(1,1000));
  5. }
  6.  
  7. function iterate($hashes) {
  8.     $count = 0;
  9.     $time_start = microtime(true);
  10.     foreach ($hashes as $hash) {
  11.         $count++;
  12.         if ($count % 1000 == 0) {
  13.             $time_end = microtime(true);
  14.             $time = $time_end - $time_start;
  15.             echo $count.' : '.$time.' : '."\n";
  16.         }
  17.     }    
  18. }
  19.  
  20. $ohashes = (object)$hashes;
  21. iterate($ohashes);
  22. echo 'Done with object'."\n";
  23. iterate($hashes);
  24. echo 'Done with array'."\n";
  25. unset($hashes);
  26. unset($ohashes);
  27.  
  28. $hashes = array();
  29. for ($x=0;$x<100000;$x++) {
  30.     $kv = sha1($x);
  31.     $hashes[$kv] = $kv;
  32. }
  33.  
  34. function iterate2($hashes) {
  35.     $count = 0;
  36.     $time_start = microtime(true);
  37.     foreach ($hashes as $key=>$value) {
  38.         $count++;
  39.         if ($count % 1000 == 0) {
  40.             $time_end = microtime(true);
  41.             $time = $time_end - $time_start;
  42.             echo $count.' : '.$time.' : '."\n";
  43.         }
  44.     }    
  45. }
  46.  
  47. $ohashes = (object)$hashes;
  48. iterate2($ohashes);
  49. echo 'Done with object'."\n";
  50. iterate2($hashes);
  51. echo 'Done with array'."\n";
  52.  
File Description
  • Array vs Obj iteration
  • PHP Code
  • 13 Jul-2021
  • 1.09 Kb
You can Share it: