TryGetValue of Dictionary C# and Performance Comparison of Judging ContainsKey and Get First

Posted by Druid on Fri, 06 Sep 2019 08:12:09 +0200

This article uses benchmarkdotnet To test the performance of a dictionary, two different ways of writing can be used when using a dictionary to obtain a possible value, so this paper analyses the performance of the two ways of writing.

The following two different methods can be used to determine the existence of a value and obtain it if it exists

One way is to use TryGetValue. See the following code

            if (Dictionary.TryGetValue(xx, out var foo))
            {
            }

Another way is to determine if there is one and then retrieve it. See the following code

if(Dictionary.ContainsKey(xx))
{
	var foo = Dictionary[xx];
}

So this article uses benchmarkdotnet Testing the performance of two methods

The following is the data for testing, and the code for testing is at the end of this article. The TryGetExist method here is to try to get a value that exists. ContainGetExist, on the other hand, first determines whether a value exists, and if it exists, attempts to obtain it.

BenchmarkDotNet=v0.10.14, OS=Windows 10.0.17134
Intel Core i7-6700 CPU 3.40GHz (Skylake), 1 CPU, 8 logical and 4 physical cores
Frequency=3328130 Hz, Resolution=300.4690 ns, Timer=TSC
  [Host]     : .NET Framework 4.7 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.3132.0  [AttachedDebugger]
  DefaultJob : .NET Framework 4.7 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.3132.0


Method Mean Error StdDev Median
TryGetExist 30.26 ns 0.6057 ns 0.5949 ns 30.11 ns
ContainGetExist 46.36 ns 1.0883 ns 3.1919 ns 44.90 ns
TryGetNoExist 20.23 ns 0.4661 ns 0.7658 ns 19.93 ns
ContainGetNoExist 18.68 ns 0.2569 ns 0.2403 ns 18.66 ns

Comparing the performance of Concurrent Dictionary thread-safe classes, that is, replacing the dictionary of the Foo test class above with that of Concurrent Dictionary without any modification. Here is the test data. You can see that the performance of using TryGetValue is still better.

BenchmarkDotNet=v0.10.14, OS=Windows 10.0.17134
Intel Core i7-6700 CPU 3.40GHz (Skylake), 1 CPU, 8 logical and 4 physical cores
Frequency=3328130 Hz, Resolution=300.4690 ns, Timer=TSC
  [Host]     : .NET Framework 4.7 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.3132.0  [AttachedDebugger]
  DefaultJob : .NET Framework 4.7 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.3132.0


Method Mean Error StdDev Median
TryGetExist 31.20 ns 0.4644 ns 0.3625 ns 31.17 ns
ContainGetExist 66.80 ns 2.4692 ns 7.2806 ns 63.84 ns
TryGetNoExist 20.07 ns 0.1254 ns 0.1112 ns 20.04 ns
ContainGetNoExist 27.63 ns 0.4230 ns 0.3956 ns 27.65 ns

All code

    public class Foo
    {
        /// <inheritdoc />
        public Foo()
        {
            var ran = new Random();
            bool set = false;
            for (int i = 0; i < 100000; i++)
            {
                LazyDictionary[ran.Next().ToString() + "-" + i.ToString()] = ran.Next().ToString();
                if (!set)
                {
                    if (ran.Next() < i)
                    {
                        set = true;
                        LazyDictionary["lindexi"] = "Teasing ratio";
                    }
                }
            }
        }

        [Benchmark]
        public void TryGetExist()
        {
            if (LazyDictionary.TryGetValue("lindexi", out var foo))
            {
                _foo = foo;
            }
        }

        [Benchmark]
        public void ContainGetExist()
        {
            if (LazyDictionary.ContainsKey("lindexi"))
            {
                _foo = LazyDictionary["lindexi"];
            }
        }


        [Benchmark]
        public void TryGetNoExist()
        {
            if (LazyDictionary.TryGetValue("lindexi123", out var foo))
            {
                _foo = foo;
            }
        }

        [Benchmark]
        public void ContainGetNoExist()
        {
            if (LazyDictionary.ContainsKey("lindexi123"))
            {
                _foo = LazyDictionary["lindexi123"];
            }
        }

        private object _foo;

        private Dictionary<string, object> LazyDictionary { get; } = new Dictionary<string, object>();

    }

My blog is about to be moved to Tencent Cloud + Community. I invite you to join us: https://cloud.tencent.com/developer/support-plan?Invite_code=19 bm8i8js1ezb.

I set up my own blog https://blog.lindexi.com/ Welcome to visit, there are many new blogs. Only when I see blogs mature will they be placed in csdn or blog park, but once they are published, they will not be updated.

If you see anything in your blog that you don't understand, welcome to communicate. I built it. dotnet Vocational and Technical College Welcome to join us


This work adopts Knowledge Sharing Signature - Noncommercial Use - Sharing 4.0 International Licensing Agreement in the Same Way License. Reprint, use and redistribute are welcome, but the article signature must be retained. Lin Dexi (Contains links: http://blog.csdn.net/lindexi_gd) and may not be used for commercial purposes. Work modified in this article must be released under the same license. If you have any questions, please contact me. contact.

Topics: Windows