Why hashset.exceptwith is twice as fast as iteration and validation! Contains in another collection?

I just did some optimizations and was puzzled by this.

My original code looked something like this:

   HashSet<IExampleAble> alreadyProcessed;//a few million items
    void someSetRoutineSlower(HashSet<IExampleAble> exampleSet)
    {

        foreach (var item in exampleSet)
        {
            if (!alreadyProcessed.Contains(item))
            {
                // do Stuff
            }
        }
    }

It took about 1.2 million ticks to process.

Then I tried the same with the exception:

 void someSetRoutineFaster(HashSet<IExampleAble> exampleSet)
    {
        exampleSet.ExceptWith(alreadyProcessed);//doesnt this have to check each item of it collection against the other one, thus actually looping twice?
        foreach (var item in exampleSet)
        {
            // do Stuff
        }
    }

and he ran with marks of about 0.4 mil-0.7 mil.

What optimization happens in this case? Is it also necessary to check all the elements, as I do in the first code fragment?

+4
source share

Source: https://habr.com/ru/post/1660475/


All Articles