Created
September 19, 2019 08:41
-
-
Save woprrr/f8d633c98b95e457a2d005c39df3edb2 to your computer and use it in GitHub Desktop.
Benchmark ArrayWalk VS FOREACH
This file contains hidden or 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 | |
$elements = []; | |
for($i = 0; $i < 100000; $i++) { | |
$elements[] = (string)rand(10000000, PHP_INT_MAX); | |
} | |
function testArrayWalk($array) { | |
$time_start = microtime(true); | |
$element = array_walk($array, 'test_walking'); | |
$time_end = microtime(true); | |
return $time_end - $time_start; | |
} | |
function test_walking(&$item1) { | |
$item1 = $item1 * 2; | |
} | |
function testForeach($array) { | |
$time_start = microtime(true); | |
foreach ($array as $key => $value) { | |
$element[$key] = $value * 2; | |
} | |
$time_end = microtime(true); | |
return $time_end - $time_start; | |
//return $element; | |
} | |
echo "Array walk took: " . number_format(testArrayWalk($elements) * 1000, 3) . "ms\n"; | |
echo "Foreach took: " . number_format(testForeach($elements) * 1000, 3) . "ms\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment