关于最优化读写,测试各个加锁:Lock、安全字典、信号量、ReaderWriterLock、ReaderWriterLockSlim

大家对于自身项目中都有本地缓存的逻辑,但这块的读写何种机制下哪个快,哪个慢,需要测试对比,以下测试报告,期望给大家一个借鉴,如果有更好的测试结果也欢迎大家一起讨论。

以下测试是开启10个并发任务对同一个字典进行10万次插入,就相当于100万次插入动作

TestLock //测试lock
Time Elapsed: ,342ms
CPU Cycles: ,,
Gen :
Gen :
Gen : TestSalfDictionary //测试线程安全字典
Time Elapsed: 259ms
CPU Cycles: ,
Gen :
Gen :
Gen : TestSemaphore //测试信号量
Time Elapsed: 588ms
CPU Cycles: ,
Gen :
Gen :
Gen : TestReaderWriterLock //测试ReaderWriterLock
Time Elapsed: ,576ms
CPU Cycles: ,
Gen :
Gen :
Gen : TestReaderWriterLockSlim //测试ReaderWriterLockSlim
Time Elapsed: 864ms
CPU Cycles: ,
Gen :
Gen :
Gen :

目前看下来安全字典的测试性能貌似最好的,ReaderWriteLock 效率最低,还不如lock,大家在今后项目中使用自己衡量一下!

关于信号量的测试代码,我贴一下,如觉得有更合理的运用它,欢迎来多多交流!

        static readonly Semaphore _semaphore = new Semaphore(, );
static readonly IDictionary<int, int> _dictionaryForSemaphore = new Dictionary<int, int>();
static void TestSemaphore()
{
for (int i = ; i < _number; i++)
{
_semaphore.WaitOne();
Random random = new Random(int.MaxValue);
var key = random.Next(int.MaxValue);
if (!_dictionaryForSemaphore.ContainsKey(key))
_dictionaryForSemaphore.Add(key, i);
_semaphore.Release();
}
}
上一篇:different styles of button in footer area


下一篇:数据结构 - 堆排序(heap sort) 具体解释 及 代码(C++)