What is the most efficient way to remove all the elements of one array from another array?

前端 未结 3 2111
有刺的猬
有刺的猬 2021-01-12 03:47

I have two arrays, array A contains a long list with some elements I want to remove. Array B is the full list of those elements that I wish to remove from array A.

W

3条回答
  •  难免孤独
    2021-01-12 04:38

    array_diff is the obvious answer, but since you've asked for the most efficient way, here's a test

    $big = range(1, 90000);
    $remove = range(500, 600);
    
    $ts = microtime(true);
    $result = array_diff($big, $remove);
    printf("%.2f\n", microtime(true) - $ts);
    
    $ts = microtime(true);
    $map = array_flip($remove);
    $result = array();
    foreach($big as $e)
        if(!isset($map[$e]))
            $result[] = $e;
    printf("%.2f\n", microtime(true) - $ts);
    

    prints on my machine

    0.67
    0.03
    

    So the simple loop with a hash-based lookup is approximately 20 times faster than array_diff.

提交回复
热议问题