Created
March 22, 2016 11:54
-
-
Save amlang/5693059e023f44f3065d to your computer and use it in GitHub Desktop.
A test to determine whether foreach or array_walk is faster
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 | |
// A test to determine whether foreach or array_walk is faster | |
$foretimes = 0; | |
for($i=0; $i < 10000; $i++){ | |
$test = array_fill(0, 10000, 'test_data'); | |
$start = microtime(true); | |
foreach ($test as $key => $value) | |
{ | |
$result[$key] = 'testdata'; | |
} | |
$end = microtime(true); | |
$foretimes += $end - $start; | |
} | |
$walktimes = 0; | |
for($i=0; $i < 10000; $i++){ | |
$test = array_fill(0, 10000, 'test_data'); | |
$start = microtime(true); | |
array_walk($test, function($value, $index) | |
{ | |
$value = 'testdata'; | |
}); | |
$end = microtime(true); | |
$walktimes += $end - $start; | |
} | |
printf("foreach time: %0.5fs\t\t%0.5fs each\n",$foretimes, $foretimes/10000); | |
printf("array_walk time: %0.5fs\t\t%0.5fs each\n",$walktimes, $walktimes/10000); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My last testresult:
(CentOS PHP 7.0)
foreach time: 4.51693s 0.00045s each
array_walk time: 13.88269s 0.00139s each