Skip to content

Instantly share code, notes, and snippets.

@matsubo
Last active December 15, 2015 12:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matsubo/5260716 to your computer and use it in GitHub Desktop.
Save matsubo/5260716 to your computer and use it in GitHub Desktop.
Benchmark of "for loop" vs "foreach range loop".
% php -v
PHP 5.3.15 with Suhosin-Patch (cli) (built: Aug 24 2012 17:45:44)
% php loop.php
0.019730806350708
0.14999198913574
7.6 times faster than range.
<?php
$times = 500000;
$start = microtime(true);
for ($i=0;$i<$times;$i++) {
}
$for = microtime(true) - $start ;
print $for ."\n";
$start = microtime(true);
foreach (range(0, $times) as $i) {
}
$range = microtime(true) - $start;
print $range ."\n";
print round($range/$for,1)." times faster than range.\n";
@matsubo
Copy link
Author

matsubo commented Mar 28, 2013

% php -v
PHP 5.4.12 (cli) (built: Mar  1 2013 09:44:40)
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2013 Zend Technologies
% php loop.php
0.020792961120605
0.24710583686829
11.9 times faster than range.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment