Created
October 28, 2013 17:41
-
-
Save sashless/7201213 to your computer and use it in GitHub Desktop.
php array_walk speedtest
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
Some speed tests | |
<?php | |
// Test results | |
$array1 = test('array_walk'); | |
$array2 = test('array_walk_list_each'); | |
$array3 = test('array_walk_foreach1'); | |
$array4 = test('array_walk_foreach2'); | |
// Check arrays for equal | |
var_dump($array1 == $array2, $array1 == $array3, $array1 == $array4); | |
// Test function 1 | |
function array_walk_list_each(&$array, $function, $userData = null) { | |
while ( list($key, $value) = each($array) ) | |
$function($array[$key], $key, $userData); | |
} | |
// Test function 2 | |
function array_walk_foreach1(&$array, $function, $userData = null) { | |
foreach ($array as $key => &$value ) | |
$function($value, $key, $userData); | |
} | |
// Test function 3 | |
function array_walk_foreach2(&$array, $function, $userData = null) { | |
foreach ($array as $key => $value ) | |
$function($array[$key], $key, $userData); | |
} | |
function some_function(&$value, $key, $userData) { | |
$value = "$key => $userData"; | |
} | |
function test($function, $count = 10000, $arrayElements = 1000) { | |
echo $function, ' ... '; | |
$array = array_fill(0, $arrayElements, "some text value"); | |
$timer = microtime(true); | |
for( $i = 0; ++$i < $count; ) | |
$function($array, 'some_function', 'some user data'); | |
printf("%.3f sec\n", microtime(true) - $timer); | |
return $array; | |
} | |
?> | |
Output (PHP 5.4.9-4ubuntu2.2 (cli) (built: Jul 15 2013 18:24:39)) | |
========================= | |
array_walk ... 13.572 sec | |
array_walk_list_each ... 0.027 sec | |
array_walk_foreach1 ... 15.356 sec | |
array_walk_foreach2 ... 17.416 sec | |
bool(true) | |
bool(true) | |
bool(true) | |
Output (PHP 5.5.0 (cli) (built: Jul 16 2013 17:59:42) - same server) | |
========================= | |
array_walk ... 4.776 sec | |
array_walk_list_each ... 0.006 sec | |
array_walk_foreach1 ... 4.482 sec | |
array_walk_foreach2 ... 5.166 sec | |
bool(true) | |
bool(true) | |
bool(true) | |
PHP 5.5 array_walk looks pretty good but list each is more and more quickly... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment