var max = 900000;
MemoryCache memoryCache = MemoryCache.Default;
Stopwatch stopwatch = Stopwatch.StartNew();
Enumerable.Range(0, max).ToList().ForEach(o =>
{
memoryCache.Add(new CacheItem(o.ToString(), o), new CacheItemPolicy()
{
});
});
var list = new List<Task>();
Enumerable.Range(0,max).ToList().ForEach(i =>
{
list.Add(Task.Run(() =>
{
// Console.WriteLine(i+" 使用memoryCache时的线程数:" + Process.GetCurrentProcess().Threads.Count);
//命中
var key = new Random(max).Next().ToString();
memoryCache.Get(key);
Thread.Sleep(1);
}));
});
Task.WaitAll(list.ToArray());
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);
list.Clear();
ConcurrentDictionary<string, object> concurrentDictionary =
new ConcurrentDictionary<string, object>();
stopwatch = Stopwatch.StartNew();
Enumerable.Range(0, max).ToList().ForEach(o => { concurrentDictionary.TryAdd(o.ToString(), o); });
list = new List<Task>();
Enumerable.Range(0,max).ToList().ForEach(i =>
{
list.Add(Task.Run(() =>
{
// Console.WriteLine(i+" 使用concurrentDictionary时的线程数:" + Process.GetCurrentProcess().Threads.Count);
//命中
var key = new Random(max).Next().ToString();
object re;
concurrentDictionary.TryGetValue(key, out re);
Thread.Sleep(1);
}));
});
Task.WaitAll(list.ToArray());
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);
执行结果
3638
1561