That seems like clearly a general utility function that could be optimized better.  See also `intersection` and `difference` in `evalfunction.c`.