Y
Y
Yakov Akulov2014-01-28 10:44:59
PHP
Yakov Akulov, 2014-01-28 10:44:59

What is the alternative to native array_intersect in PHP?

Probably many people know about it.
We are writing a simple function to find the intersection of two arrays without keys.
Something like that

function array_intersect2($a, $b) {
    $al = count($a);
    $bl = count($b);
    sort($a);
    sort($b);
    $max = ($a[$al - 1] > $b[$bl - 1]) ?
        $a[$al - 1] :
        $b[$bl - 1];
    $min = ($a[0] < $b[0]) ?
        $a[0] :
        $b[0];
    $c = array();
    foreach($a as $i) {
        if($i > $min && $i < $max) {
            $c[] = $i;
        }
    }
    foreach($b as $i) {
        if($i > $min && $i < $max) {
            $c[] = $i;
        }
    }

    return $c;
}

Next, we run a simple test for the intersection of two arrays
. For example, these:
$a = array();
$b = array();
for($i = 0; $i < 50000; $i++) {
    $a[] = mt_rand(0, 100000);
    $b[] = mt_rand(0, 100000);
}

in the test we compare the performance of array_intersect and array_intersect2
My own implementation consistently outperforms the native function in performance. Considering that any php programmer knows it's always better to use native functions versus php implementations, this kind of performance seems very odd for array_intersect. Why is this happening?
Really developers of php could not provide such special cases of arrays (without keys and easily giving in to sorting)?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vitaly Zheltyakov, 2014-01-28
@VitaZheltyakov

You have some kind of limitation in the function that gives the payoff. This is normal.
For example, I use my self-written json_encode function with a restriction on the dimension of arrays. Due to this (the extra check is_array is eliminated), my self-written function is about 3 times faster than the native one.

V
Vadim Yakovlev, 2014-01-28
@FrimInc

You have numeric arrays. Try with other types of values, such as long strings.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question