当请求Queue.Synchonized 时,你会得到一个SynchronizedQueue 作为回报,它在内部队列上对Enqueue 和Dequeue 的调用很少使用lock。因此,性能应该与使用Queue 并使用自己的lock 管理锁定Enqueue 和Dequeue 相同。
你确实在想象事物——它们应该是一样的。
更新
事实上,当使用SynchronizedQueue 时,您正在添加一个间接层,因为您必须通过包装器方法才能到达它所管理的内部队列。如果有的话,这应该会大大减慢速度,因为堆栈上有一个额外的帧需要为每次调用进行管理。上帝知道内联是否会取消这一点。无论如何 - 它是最小的。
更新 2
我现在已经对此进行了基准测试,并且正如我之前的更新中所预测的那样:
“Queue.Synchronized”比“Queue+lock”慢
我进行了单线程测试,因为它们都使用相同的锁定技术(即lock),因此以“直线”测试纯开销似乎是合理的。
我的基准测试为 Release 构建产生了以下结果:
Iterations :10,000,000
Queue+Lock :539.14ms
Queue+Lock :540.55ms
Queue+Lock :539.46ms
Queue+Lock :540.46ms
Queue+Lock :539.75ms
SynchonizedQueue:578.67ms
SynchonizedQueue:585.04ms
SynchonizedQueue:580.22ms
SynchonizedQueue:578.35ms
SynchonizedQueue:578.57ms
使用以下代码:
private readonly object _syncObj = new object();
[Test]
public object measure_queue_locking_performance()
{
const int TestIterations = 5;
const int Iterations = (10 * 1000 * 1000);
Action<string, Action> time = (name, test) =>
{
for (int i = 0; i < TestIterations; i++)
{
TimeSpan elapsed = TimeTest(test, Iterations);
Console.WriteLine("{0}:{1:F2}ms", name, elapsed.TotalMilliseconds);
}
};
object itemOut, itemIn = new object();
Queue queue = new Queue();
Queue syncQueue = Queue.Synchronized(queue);
Action test1 = () =>
{
lock (_syncObj) queue.Enqueue(itemIn);
lock (_syncObj) itemOut = queue.Dequeue();
};
Action test2 = () =>
{
syncQueue.Enqueue(itemIn);
itemOut = syncQueue.Dequeue();
};
Console.WriteLine("Iterations:{0:0,0}\r\n", Iterations);
time("Queue+Lock", test1);
time("SynchonizedQueue", test2);
return itemOut;
}
[SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.GC.Collect")]
private static TimeSpan TimeTest(Action action, int iterations)
{
Action gc = () =>
{
GC.Collect();
GC.WaitForFullGCComplete();
};
Action empty = () => { };
Stopwatch stopwatch1 = Stopwatch.StartNew();
for (int j = 0; j < iterations; j++)
{
empty();
}
TimeSpan loopElapsed = stopwatch1.Elapsed;
gc();
action(); //JIT
action(); //Optimize
Stopwatch stopwatch2 = Stopwatch.StartNew();
for (int j = 0; j < iterations; j++) action();
gc();
TimeSpan testElapsed = stopwatch2.Elapsed;
return (testElapsed - loopElapsed);
}