Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>AddIfNotPresent does an additional divide that Contains doesn't perform. Take a look at the IL for Contains:</p> <pre><code>IL_000a: call instance int32 class System.Collections.Generic.HashSet`1&lt;!T&gt;::InternalGetHashCode(!0) IL_000f: stloc.0 IL_0010: ldarg.0 IL_0011: ldfld int32[] class System.Collections.Generic.HashSet`1&lt;!T&gt;::m_buckets IL_0016: ldloc.0 IL_0017: ldarg.0 IL_0018: ldfld int32[] class System.Collections.Generic.HashSet`1&lt;!T&gt;::m_buckets IL_001d: ldlen IL_001e: conv.i4 IL_001f: rem IL_0020: ldelem.i4 IL_0021: ldc.i4.1 IL_0022: sub IL_0023: stloc.1 </code></pre> <p>This is computing the bucket location for the hash code. The result is saved at local memory location 1.</p> <p>AddIfNotPresent does something similar, but it also saves the computed value at location 2, so that it can insert the item into the hash table at that position if the item doesn't exist. It does that save because one of the locations is modified later in the loop that goes looking for the item. Anyway, here's the relevant code for AddIfNotPresent:</p> <pre><code>IL_0011: call instance int32 class System.Collections.Generic.HashSet`1&lt;!T&gt;::InternalGetHashCode(!0) IL_0016: stloc.0 IL_0017: ldloc.0 IL_0018: ldarg.0 IL_0019: ldfld int32[] class System.Collections.Generic.HashSet`1&lt;!T&gt;::m_buckets IL_001e: ldlen IL_001f: conv.i4 IL_0020: rem IL_0021: stloc.1 IL_0022: ldarg.0 IL_0023: ldfld int32[] class System.Collections.Generic.HashSet`1&lt;!T&gt;::m_buckets IL_0028: ldloc.0 IL_0029: ldarg.0 IL_002a: ldfld int32[] class System.Collections.Generic.HashSet`1&lt;!T&gt;::m_buckets IL_002f: ldlen IL_0030: conv.i4 IL_0031: rem IL_0032: ldelem.i4 IL_0033: ldc.i4.1 IL_0034: sub IL_0035: stloc.2 </code></pre> <p>Anyway, I think the extra divide is what's causing Add to take more time than Contains. At first glance, it looks like that extra divide could be factored out, but I can't say for sure without spending a little more time deciphering the IL.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload