Skip to content

Instantly share code, notes, and snippets.

@robertmarsal
Created November 22, 2011 12:27
Show Gist options
  • Save robertmarsal/1385558 to your computer and use it in GitHub Desktop.
Save robertmarsal/1385558 to your computer and use it in GitHub Desktop.
Array_Map vs Foreach Benchmark
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
function microtimestamp() {
$timeofday = gettimeofday();
return $timeofday['sec'] + $timeofday['usec'] /
1000000;
}
function add($x){
return $x++;
}
//Setup
unset($hthousand);
for($i=0;$i<99999;$i++){
$hthousand[$i] = (rand()%2);
}
//Foreach
$start = microtimestamp();
foreach($hthousand as $key => $value){
$hthousand[$key] = ($value+1);
}
$end = microtimestamp();
$result = ($end-$start);
echo "Foreach: ".$result."<br>";
//Array_Map(Value)
$start = microtimestamp();
array_map('add',$hthousand);
$end = microtimestamp();
$result = ($end-$start);
echo "Array_Map(Value): ".$result."<br>";
//Array_Map(Reference)
$start = microtimestamp();
array_map('add',&$hthousand);
$end = microtimestamp();
$result = ($end-$start);
echo "Array_Map(Reference): ".$result;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment