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
并发性能比较:MemoryCache vs ConcurrentDictionary
这篇博客对比了MemoryCache和ConcurrentDictionary在高并发环境下的性能。通过创建并填充大量条目,然后并发读取,结果显示ConcurrentDictionary在处理并发任务时的效率显著高于MemoryCache,执行时间仅为MemoryCache的一半左右。
1994





