Skip to content

Instantly share code, notes, and snippets.

@amlang
Created March 22, 2016 11:54
Show Gist options
  • Save amlang/5693059e023f44f3065d to your computer and use it in GitHub Desktop.
Save amlang/5693059e023f44f3065d to your computer and use it in GitHub Desktop.
A test to determine whether foreach or array_walk is faster
<?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);
?>
@amlang
Copy link
Author

amlang commented Mar 22, 2016

My last testresult:
(CentOS PHP 7.0)

foreach time: 4.51693s 0.00045s each
array_walk time: 13.88269s 0.00139s each

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment