Created
November 4, 2014 08:44
-
-
Save oanhnn/1a893702652ed8b91ba7 to your computer and use it in GitHub Desktop.
test performance of array_diff on PHP
This file contains 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 | |
function my_array_diff($a, $b) | |
{ | |
$map = $out = array(); | |
foreach ($a as $val) | |
$map[$val] = 1; | |
foreach ($b as $val) | |
if (isset($map[$val])) | |
$map[$val] = 0; | |
foreach ($map as $val => $ok) | |
if ($ok) | |
$out[] = $val; | |
return $out; | |
} | |
function your_array_diff($arraya, $arrayb) | |
{ | |
foreach ($arraya as $keya => $valuea) { | |
if (in_array($valuea, $arrayb)) { | |
unset($arraya[$keya]); | |
} | |
} | |
return $arraya; | |
} | |
function leo_array_diff($a, $b) | |
{ | |
$map = $out = array(); | |
foreach ($a as $val) | |
$map[$val] = 1; | |
foreach ($b as $val) | |
unset($map[$val]); | |
return array_keys($map); | |
} | |
function flip_array_diff_key($b, $a) | |
{ | |
$at = array_flip($a); | |
$bt = array_flip($b); | |
$d = array_diff_key($bt, $at); | |
return array_keys($d); | |
} | |
function flip_isset_diff($b, $a) | |
{ | |
$at = array_flip($a); | |
$d = array(); | |
foreach ($b as $i) | |
if (!isset($at[$i])) | |
$d[] = $i; | |
return $d; | |
} | |
function large_array_diff($b, $a) | |
{ | |
$at = array(); | |
foreach ($a as $i) | |
$at[$i] = 1; | |
$d = array(); | |
foreach ($b as $i) | |
if (!isset($at[$i])) | |
$d[] = $i; | |
return $d; | |
} | |
$a = range(1, 20000); | |
$b = range(5000, 25000); | |
shuffle($a); | |
shuffle($b); | |
$ts = microtime(true); | |
array_diff($a, $b); | |
printf("PHP =%.4f\n", microtime(true) - $ts); | |
$ts = microtime(true); | |
my_array_diff($a, $b); | |
printf("my_array_diff =%.4f\n", microtime(true) - $ts); | |
$ts = microtime(true); | |
your_array_diff($a, $b); | |
printf("your_array_diff =%.4f\n", microtime(true) - $ts); | |
$ts = microtime(true); | |
leo_array_diff($a, $b); | |
printf("leo_array_diff =%.4f\n", microtime(true) - $ts); | |
$ts = microtime(true); | |
flip_array_diff_key($a, $b); | |
printf("flip_array_diff_key =%.4f\n", microtime(true) - $ts); | |
$ts = microtime(true); | |
flip_isset_diff($a, $b); | |
printf("flip_isset_diff =%.4f\n", microtime(true) - $ts); | |
$ts = microtime(true); | |
large_array_diff($a, $b); | |
printf("large_array_diff =%.4f\n", microtime(true) - $ts); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment