using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Profiling;
namespace MyTest
{
public class TestDictionary : MonoBehaviour
{
public Dictionary<int, int> testMap;
public int TestCount = 10000;
void Start()
{
testMap = new Dictionary<int, int>();
testMap.Add(1, 1);
}
void Update()
{
Profiler.BeginSample("DeleteAndAdd");
DeleteAndAdd();
Profiler.EndSample();
Profiler.BeginSample("OverrideAndAdd");
OverrideAndAdd();
Profiler.EndSample();
}
void DeleteAndAdd()
{
for (int i = 0; i < TestCount; i++)
{
testMap.SetValue(1, 1);
}
}
void OverrideAndAdd()
{
for (int i = 0; i < TestCount; i++)
{
testMap.SetValue2(1, 1);
}
}
}
public static class DictionaryExtension
{
/// <summary>
/// 先删除再添加
/// </summary>
public static void SetValue<T, V>(this Dictionary<T, V> dic, T key, V value)
{
if (dic.ContainsKey(key))
{
dic.Remove(key);
}
}
/// <summary>
/// 直接覆盖
/// </summary>
public static void SetValue2<T, V>(this Dictionary<T, V> dic, T key, V value)
{
if (dic.ContainsKey(key))
{
dic[key] = value;
}
}
}
}
结果证明,Dictionary先删除再添加竟然和直接覆盖相比差不多的性能,而且还快那么一丁点儿,神奇!