Note that there are some explanatory texts on larger screens.

plurals
  1. POHashSet performance Add vs Contains for existing elements
    primarykey
    data
    text
    <p>For some reason, it seems the <code>Add</code> operation on a <code>HashSet</code> is slower than the <code>Contains</code> operation when the element already exists in the <code>HashSet</code>. </p> <p>Here is proof: </p> <pre><code> Stopwatch watch = new Stopwatch(); int size = 10000; int iterations = 10000; var s = new HashSet&lt;int&gt;(); for (int i = 0; i &lt; size; i++) { s.Add(i); } Console.WriteLine(watch.Time(() =&gt; { for (int i = 0; i &lt; size; i++) { s.Add(i); } }, iterations)); s = new HashSet&lt;int&gt;(); for (int i = 0; i &lt; size; i++) { s.Add(i); } // outputs: 47,074,764 Console.WriteLine(watch.Time(() =&gt; { for (int i = 0; i &lt; size; i++) { if (!s.Contains(i)) s.Add(i); } }, iterations)); // outputs: 41,125,219 </code></pre> <p>Why is <code>Contains</code> faster than <code>Add</code> for already-existing elements? </p> <p>Note: I'm using this <code>Stopwatch</code> extension from another SO question.</p> <pre><code> public static long Time(this Stopwatch sw, Action action, int iterations) { sw.Reset(); sw.Start(); for (int i = 0; i &lt; iterations; i++) { action(); } sw.Stop(); return sw.ElapsedTicks; } </code></pre> <p><strong>UPDATE</strong>: Internal testing has revealed that the big performance diff only happens on the x64 version of the .NET framework. With the 32 bit version of the framework Contains seems run at identical speed to add (in fact it appears that the version with the contains runs a percent slower in some test runs) On X64 versions of the framework, the version with the contains seems to run about 15% faster. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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