Created
October 10, 2011 10:58
-
-
Save dundee/1275043 to your computer and use it in GitHub Desktop.
Rychlost foreach vs array_map
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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ý.