note 111563 added to function.array-intersect
| From: | MikeBlock | Date: | Mon, 04 Mar 2013 21:27:21 +0000 |
| Subject: | note 111563 added to function.array-intersect | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-193893@lists.php.net to get a copy of this message | ||
I bench-marked some uses of array_intersect and can't believe how slow it is. This isn't
as elaborate, but handles most cases and is much faster:
<?php
/**
examines two arrays and returns the intersected arrays with matching keys (ignores duplicate keys)
*/
function simple_array_intersect($a,$b) {
$a_assoc = $a != array_values($a);
$b_assoc = $b != array_values($b);
$ak = $a_assoc ? array_keys($a) : $a;
$bk = $b_assoc ? array_keys($b) : $b;
$out = array();
for ($i=0;$i<sizeof($ak);$i++) {
if (in_array($ak[$i],$bk)) {
if ($a_assoc) {
$out[$ak[$i]] = $a[$ak[$i]];
} else {
$out[] = $ak[$i];
}
}
}
return $out;
}
?>
You can try this out with this:
<?php
// create a large array (simple)
$first = array();
for ($i=500;$i<500000;$i++) {
$first[] = $i;
}
// create a smaller array (associative)
$second = array();
for ($i=499990;$i<500000;$i++) {
$second[$i] = rand();
}
echo microtime(true)."\n";
// built-in function
print_r(array_intersect($first,$second));
echo microtime(true)."\n";
// favour simple array as match
print_r(simple_array_intersect($first,$second));
echo microtime(true)."\n";
// favour associative keys for match
print_r(simple_array_intersect($second,$first));
echo microtime(true)."\n";
?>
----
Server IP: 69.147.83.199
Probable Submitter: 99.241.44.202
----
Manual Page -- http://php.net/manual/en/function.array-intersect.php
Edit -- https://master.php.net/note/edit/111563
Del: integrated -- https://master.php.net/note/delete/111563/integrated
Del: useless -- https://master.php.net/note/delete/111563/useless
Del: bad code -- https://master.php.net/note/delete/111563/bad+code
Del: spam -- https://master.php.net/note/delete/111563/spam
Del: non-english -- https://master.php.net/note/delete/111563/non-english
Del: in docs -- https://master.php.net/note/delete/111563/in+docs
Del: other reasons-- https://master.php.net/note/delete/111563
Reject -- https://master.php.net/note/reject/111563
Search -- https://master.php.net/manage/user-notes.php