Skip to content

Instantly share code, notes, and snippets.

@dundee
Created October 10, 2011 10:58
Show Gist options
  • Save dundee/1275043 to your computer and use it in GitHub Desktop.
Save dundee/1275043 to your computer and use it in GitHub Desktop.
Rychlost foreach vs array_map
<?php
$x = 3;
$max = 1000000;
$arr = array(
1,
2,
3,
);
$start = microtime(TRUE);
$f = function($v) {
return $v + 1;
};
for ($i = 0; $i < $max; $i++) {
if ($x == 1) {
// klasicky
$out = array();
foreach ($arr as $v) {
$out[] = $v + 1;
}
} elseif ($x == 2) {
// funkcionalne
$out2 = array_map(function($v) {
return $v + 1;
}, $arr);
} else {
// funcionalne bez tvoreni closure
$out2 = array_map($f, $arr);
}
}
$end = microtime(TRUE);
echo round($end - $start, 5) . 's';
// 3.74634s vs 18.0812s vs 17.36669s
@NoxArt
Copy link

NoxArt commented Dec 1, 2013

Obávám se, že test není správný ... u 2. a 3. varianty se imho udělá 1000000 porovnání $x == 2 navíc. Vzhledem k tomu jak malé $arr je, výsledek bude nejspíš ovlivněný.

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