Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 171229
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T12:57:02+00:00 2026-05-11T12:57:02+00:00

For some reason, it seems the Add operation on a HashSet is slower than

  • 0

For some reason, it seems the Add operation on a HashSet is slower than the Contains operation when the element already exists in the HashSet.

Here is proof:

    Stopwatch watch = new Stopwatch();     int size = 10000;     int iterations = 10000;       var s = new HashSet<int>();     for (int i = 0; i < size; i++) {         s.Add(i);     }      Console.WriteLine(watch.Time(() =>     {         for (int i = 0; i < size; i++) {             s.Add(i);         }     }, iterations));      s = new HashSet<int>();     for (int i = 0; i < size; i++) {         s.Add(i);     }      // outputs: 47,074,764      Console.WriteLine(watch.Time(() =>     {         for (int i = 0; i < size; i++) {             if (!s.Contains(i))                 s.Add(i);         }     }, iterations));      // outputs: 41,125,219 

Why is Contains faster than Add for already-existing elements?

Note: I’m using this Stopwatch extension from another SO question.

    public static long Time(this Stopwatch sw, Action action, int iterations) {         sw.Reset();         sw.Start();         for (int i = 0; i < iterations; i++) {             action();         }         sw.Stop();          return sw.ElapsedTicks;     } 

UPDATE: 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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-11T12:57:03+00:00Added an answer on May 11, 2026 at 12:57 pm

    AddIfNotPresent does an additional divide that Contains doesn’t perform. Take a look at the IL for Contains:

    IL_000a:  call       instance int32 class System.Collections.Generic.HashSet`1<!T>::InternalGetHashCode(!0)   IL_000f:  stloc.0   IL_0010:  ldarg.0   IL_0011:  ldfld      int32[] class System.Collections.Generic.HashSet`1<!T>::m_buckets   IL_0016:  ldloc.0   IL_0017:  ldarg.0   IL_0018:  ldfld      int32[] class System.Collections.Generic.HashSet`1<!T>::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 

    This is computing the bucket location for the hash code. The result is saved at local memory location 1.

    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:

    IL_0011:  call       instance int32 class System.Collections.Generic.HashSet`1<!T>::InternalGetHashCode(!0)   IL_0016:  stloc.0   IL_0017:  ldloc.0   IL_0018:  ldarg.0   IL_0019:  ldfld      int32[] class System.Collections.Generic.HashSet`1<!T>::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<!T>::m_buckets   IL_0028:  ldloc.0   IL_0029:  ldarg.0   IL_002a:  ldfld      int32[] class System.Collections.Generic.HashSet`1<!T>::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 

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

For some reason, the event listener I define never seems to receive any events,
For some reason I never see this done. Is there a reason why not?
For some reason when I attempt to make a request to an Ajax.net web
For some reason when I create a new namespace in Visual Studio 2008 its
For some reason, when I try to install SQL Server 2008 Express , I
For some reason, lately the *.UDL files on many of my client systems are
For some reason, Section 1 works but Section 2 does not. When run in
For some reason beyond me I can't access the mysql server on a machine.
For some reason the Windows command prompt is special in that you have to
For some reason after I installed Boot Camp, my os x terminal started to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.