Skip to content

Instantly share code, notes, and snippets.

@BraveSirRobin
Created May 15, 2011 13:24
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 BraveSirRobin/973159 to your computer and use it in GitHub Desktop.
Save BraveSirRobin/973159 to your computer and use it in GitHub Desktop.
Array speed tests
<?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