Skip to content

Instantly share code, notes, and snippets.

@woprrr
Created September 19, 2019 08:41
Show Gist options
  • Save woprrr/f8d633c98b95e457a2d005c39df3edb2 to your computer and use it in GitHub Desktop.
Save woprrr/f8d633c98b95e457a2d005c39df3edb2 to your computer and use it in GitHub Desktop.
Benchmark ArrayWalk VS FOREACH
<?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