Created
May 15, 2011 13:24
-
-
Save BraveSirRobin/973159 to your computer and use it in GitHub Desktop.
Array speed tests
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 = array(); | |
for ($i = 0; $i < 1000; $i++) { | |
$a[] = rand(0,1000000); | |
} | |
printf("Start, first mine:\n"); | |
$t1 = microtime(true); | |
var_dump(mine($a)); | |
$t2 = microtime(true); | |
printf("\nDone in %f.\n\nNow Emil's:\n", $t2 - $t1); | |
$t1 = microtime(true); | |
var_dump(emils($a)); | |
$t2 = microtime(true); | |
printf("\nDone in %f\n", $t2 - $t1); | |
function mine ($a) { | |
asort($a); | |
return array_slice($a, -4); | |
} | |
function emils ($array) { | |
$a = $b = $c = $d = null; | |
foreach($array as $v) { | |
if(!isset($a) || $v > $a) { | |
$d = $c; | |
$c = $b; | |
$b = $a; | |
$a = $v; | |
}elseif(!isset($b) || $v > $b) { | |
$d = $c; | |
$c = $b; | |
$b = $v; | |
}elseif(!isset($c) || $v > $c) { | |
$d = $c; | |
$c = $v; | |
}elseif(!isset($d) || $v > $d) { | |
$d = $v; | |
} | |
} | |
// return array_slice($array, -4); This old version was wrong!! | |
return array($a, $b, $c, $d); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment