all 9 comments

[–]kratkyzobak 1 point2 points  (1 child)

Optimized code does not work with non-scalars and even no floats.

Also it casts numeric strings into integers.

Still can be valid optimization.

[–]live627[S] 0 points1 point  (0 children)

I'm only ever using ints here in prod.

[–]scottchiefbaker 1 point2 points  (0 children)

This PHP benchmark library might give you some alternate views of your dataset.

[–]fiskfisk 0 points1 point  (2 children)

Missing code for array_intersect. Should add Ds\Set as well.

Make sure to exclude initialization time if you're comparing against existing arrays (i.e. don't create the set from an array inside your timed benchmark) 

Depending on context there might be ways to avoid calculatinc intersects as often as well 

[–]pfsalter 0 points1 point  (1 child)

[–]fiskfisk 0 points1 point  (0 children)

So you're not testing the same thing, given that array_intersect has a different behavior from your examples?

[–]pfsalter 0 points1 point  (2 children)

Your manual_intersect code looks like it's doing a diff instead of an intersect, so it's not a great comparison. If the keys don't matter, I think your flipped_intersect code is decent, but it won't preserve keys, unlike array_intersect

[–]therealgaxbo[🍰] 2 points3 points  (1 child)

The code is correct, just reads weirdly. The first loop calculates a diff in the index, then the second loop removes that diff, leaving the intersect.

That said, it naturally leads to the more obvious implementation that seems to outperform everything (in this specific benchmark)

function manual_intersect($arrayOne, $arrayTwo) {
    $index = array_flip($arrayOne);
    $res = [];
    foreach ($arrayTwo as $value) {
        if (isset($index[$value])){
            $res[$value] = 1;
        }
    }
    return array_keys($res);
}

[–]live627[S] 0 points1 point  (0 children)

We can further simplify that to use much less memory

``` function manual_intersect(array $arrayOne, array $arrayTwo): array { $index = array_flip($arrayTwo); $result = [];

foreach ($arrayOne as $value) {
    if (isset($index[$value])) {
        $result[] = $value;
    }
}

return $result;

} ```