For or Foreach? PHP vs. Javascript, C++, Java, HipHop (update: HHVM v2)
Lessons learned: Foreach is 4-5 times faster than For Nested Foreach is 4-5 times faster than nested For Foreach with key lookup is 2 times slower than Foreach without C++ is 60 times faster than PHP running For/Foreach on Arrays Javascript is 2-20 times slower than C++/Java running For on Arrays HipHop is currently no alternative to C++ Using a better CPU makes the code 4-5 times faster Here is a sample script, running on a 1.4 GHz machine with PHP 5.4.0: // init arrays $array = array(); for ($i=0; $i<50000; $i++) $array[] = $i*2; $array2 = array(); for ($i=20000; $i<21000; $i++) $array2[] = $i*2; // test1: foreach big-array (foreach small-array) $start = microtime(true); foreach ($array as $val) { foreach ($array2 as $val2) if ($val == $val2) {} } echo (microtime(true)-$start)."\n"; // test1b: foreach big-array (foreach small-array) $start = microtime(true); foreach ($array as $val) { foreach ($array2 as $val2) if ($val === $val2) {} } echo (microtime(true)-$st