[C# 문법] Dictionary ContainsKey vs TeyGetValue 성능 차이

참조



Dictionary ContainsKey vs TeyGetValue 성능 차이

  • Dictionary 사용시 ContainsKey 메서드와 TryGetValue 메서드의 속도차이를 비교 하였습니다.


ContainsKey, TryGetValue 메서드 원형

  • ContainsKey, TryGetValue 메서드 속도 비교에 앞서 각 메서드의 원형에 대해서 살펴 보겠습니다.

ContainsKey 메서드 원형

public bool ContainsKey(TKey key)
{
    return (this.FindEntry(key) >= 0);
}

TryGetValue 메서드 원형

public bool TryGetValue(TKey key, out TValue value)
{
    int index = this.FindEntry(key);
    if (index >= 0)
    {
        value = this.entries[index].value;
        return true;
    }
    value = defaule(TValue);
    return false;
}


ContainsKey vs TryGetValue 메서드 속도 비교

  • 속도 분석은 BenchmarkDotNet NuGet 패키지를 설치하여 비교하였습니다.
  • 테스트 프로그램은 반복을 천만번 하면서, dictionary 객체 dic에 저장되어 있는 Key 값인 'a', 'b' 를 ContainsKey 메서드와 TryGetValue 메서드를 이용하여 비교하는 구문입니다.
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System;
using System.Collections.Generic;

namespace ConsoleApp8
{
    class Program
    {
        static void Main(string[] args)
        {
            var summary = BenchmarkRunner.Run<DictionaryTest>();
        }
    }

    [MemoryDiagnoser]
    public class DictionaryTest
    {
        [Benchmark]
        public void ContainsDictionary()
        {
            var dic = new Dictionary<string, string> { { "a", "b" } };

            for (int i = 0; i != 10000000; i++)
            {
                string data = string.Empty;
                data = dic.ContainsKey("a") == true ? dic["a"] : default(string);
                data = dic.ContainsKey("b") == true ? dic["b"] : default(string);
            }
        }

        [Benchmark]
        public void TryGetValueDictionary()
        {
            var dic = new Dictionary<string, string> { { "a", "b" } };

            for (int i = 0; i != 10000000; i++)
            {
                string value;
                if (!dic.TryGetValue("a", out value))
                {
                    throw new ApplicationException("Oops");
                }
                if (dic.TryGetValue("b", out value))
                {
                    throw new ApplicationException("Oops");
                }
            }
        }
    }
}


실행 결과

  • 위의 코드를 Benchmark 돌려 본 결과, TryGetValue 메서드가 좀더 빠른것을 확인하였습니다.



정리

  • Dictionary ContainsKey, TryGetValue 메서드 단순 비교 시에는 TryGetValue 메서드가 좀 더 성능이 빨랐습니다.
728x90

이 글을 공유하기

댓글

Designed by JB FACTORY