Skip to content

Instantly share code, notes, and snippets.

@masakielastic
Created January 15, 2012 01:40
Show Gist options
  • Save masakielastic/1613810 to your computer and use it in GitHub Desktop.
Save masakielastic/1613810 to your computer and use it in GitHub Desktop.
iterator_apply() と foreach の比較
<?php
// modified the code from https://gist.github.com/1287753
// see also: https://github.com/zendframework/zf2/pull/502
//
// the result on my Macbook Pro
//
// foreach : 1.3991289138794
// array_map : 1.8903770446777
// iterator_apply: 4.6320548057556
ini_set('max_execution_time', 900);
function timer(callback $block) {
$start = microtime(true);
for ($i = 0; $i < 100000; ++$i) {
$block();
}
$end = microtime(true);
return $end - $start;
}
$data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
$iterator = new ArrayIterator($data);
$foreachTime = timer(function() use ($data) {
$result = [];
foreach ($data as $key => $value) {
$result[$key] = $value * 2;
}
});
$mapTime = timer(function() use ($data) {
$result = [];
$result = array_map(function ($value) { return $value * 2; }, $data);
});
$iteratorTime = timer(function() use ($data, $iterator) {
$result = [];
iterator_apply($iterator, function() use ($result, $iterator) {
$result[$iterator->key()] = $iterator->current() * 2;
return true;
});
});
printf('foreach : %s' . PHP_EOL, $foreachTime);
printf('array_map : %s' . PHP_EOL, $mapTime);
printf('iterator_apply: %s' . PHP_EOL, $iteratorTime);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment