ContainsKey VS TryGetValue
각각의 함수는 Dictionary 자료구조에서 키를 찾는 함수이다.
두 함수를 비교하여 어떤 함수가 더 빠른지 그리고 왜 빠른지 알아보도록 하겠습니다.
각각의 함수를 1000번씩 호출해보겠습니다.
ContainsKey
Dictionary<string, int> dic = new Dictionary<string, int>();
private void Awake() {
int len = 100000000;
int outValue; dic["str"] = 1;
sw.Start();
for ( int i = 0; i < len; i++ ) {
if (dic.ContainsKey("str") == true) {
outValue = dic["str"]; }
}
sw.Stop();
UnityEngine.Debug.Log(sw.ElapsedMilliseconds);
}
TryGetValue
Dictionary<string, int> dic = new Dictionary<string, int>();
private void Awake() {
int len = 100000000;
int outValue; dic["str"] = 1;
sw.Start();
for ( int i = 0; i < len; i++ ) {
dic.TryGetValue( "str", out outValue );
}
sw.Stop();
UnityEngine.Debug.Log(sw.ElapsedMilliseconds);
}
ContainsKey | TryGetValue |
4048 ms | 2117 ms |
2배의 속도 차이가 나는 것을 볼 수 있습니다.
동작하는 방식은 내부적으로는 같지만 ContainsKey는 값을 담기 위해서 한번더 참조를 해야하는 문제로 시작이 배로 걸리는 현상입니다. 하지만 단순히 키가 있는지만 알고 싶다면 오히려 ContainsKey가 조금 더 빠른 결과를 보여줍니다.
*Key만 찾기
ContainsKey | TryGetValue |
2087 ms | 2116 ms |
결론은 대부분의 상황에서 TryGetValue를 사용하자!
'유니티 > Performance' 카테고리의 다른 글
애니메이션 퍼포먼스 비교 (0) | 2025.05.18 |
---|---|
유니티 - ref, out, (in + 데미지 최적화) (0) | 2025.04.14 |
Unity - 자식 클래스 참조 비교 (0) | 2025.03.20 |
Unity - GetComponent 위치에 따른 퍼포먼스 (0) | 2025.03.20 |
Unity - Json 비교 (0) | 2025.03.20 |