Skip to content

Instantly share code, notes, and snippets.

@dariuskasperavicius
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dariuskasperavicius/2089cc8a10d053da2b17 to your computer and use it in GitHub Desktop.
Save dariuskasperavicius/2089cc8a10d053da2b17 to your computer and use it in GitHub Desktop.
foreach vs array_walk
<?php
$testBase = array_fill(0, 100000, 'testdata');
echo "Test array count: " . count($testBase) . PHP_EOL;
for($x = 0; $x < 10; $x++ ) {
echo "Test #$x" . PHP_EOL;
/* foreach test */
$testCopy = array();
$before = microtime(true);
foreach ($testBase as $key => $value) {
$testCopy[$key] = $value . 'asdasd';
}
$after = microtime(true);
$dif = $after - $before;
echo "foreach test ($before, $after): $dif" . PHP_EOL;
/* array_walk test */
$testCopy = $testBase;
$before2 = microtime(true);
array_walk($testCopy, function(&$value, $key) {
$value = $value . 'qweqwe';
});
$after2 = microtime(true);
$dif2 = $after2 - $before2;
echo "array_walk test ($before2, $after2): $dif2" . PHP_EOL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment