关于最优化读写,测试各个加锁:Lock、安全字典、信号量、ReaderWriterLock、ReaderWriterLockSlim
大家对于自身项目中都有本地缓存的逻辑,但这块的读写何种机制下哪个快,哪个慢,需要测试对比,以下测试报告,期望给大家一个借鉴,如果有更好的测试结果也欢迎大家一起讨论。
以下测试是开启10个并发任务对同一个字典进行10万次插入,就相当于100万次插入动作
TestLock //测试lock Time Elapsed: 1,342ms CPU Cycles: 56,099,316 Gen 0: 67 Gen 1: 1 Gen 2: 0 TestSalfDictionary //测试线程安全字典 Time Elapsed: 259ms CPU Cycles: 268,257 Gen 0: 67 Gen 1: 0 Gen 2: 0 TestSemaphore //测试信号量 Time Elapsed: 588ms CPU Cycles: 285,531 Gen 0: 67 Gen 1: 0 Gen 2: 0 TestReaderWriterLock //测试ReaderWriterLock Time Elapsed: 4,576ms CPU Cycles: 241,155 Gen 0: 67 Gen 1: 0 Gen 2: 0 TestReaderWriterLockSlim //测试ReaderWriterLockSlim Time Elapsed: 864ms CPU Cycles: 288,810 Gen 0: 67 Gen 1: 0 Gen 2: 0
目前看下来安全字典的测试性能貌似最好的,ReaderWriteLock 效率最低,还不如lock,大家在今后项目中使用自己衡量一下!
关于信号量的测试代码,我贴一下,如觉得有更合理的运用它,欢迎来多多交流!
static readonly Semaphore _semaphore = new Semaphore(10, 10); static readonly IDictionary<int, int> _dictionaryForSemaphore = new Dictionary<int, int>(); static void TestSemaphore() { for (int i = 0; i < _number; i++) { _semaphore.WaitOne(100); Random random = new Random(int.MaxValue); var key = random.Next(int.MaxValue); if (!_dictionaryForSemaphore.ContainsKey(key)) _dictionaryForSemaphore.Add(key, i); _semaphore.Release(); } }