.net事件的性能影响 [英] Performance implications of .net Events
问题描述
我明白了滥用的担忧,我知道他们只是一个特殊的多播代理,最多有一个监听者为什么在方法调用中使用事件被认为是昂贵的?
更新:
只是要清楚这不是关于任何特定的实现,这是一个更通用的问题,关于在方法调用中使用事件的成本。
在你的场景中测试 - 我会想到很多很多因素都会影响到这一点,特别是当我们用一种如此低的相对成本来说话时,调用
一个快速简单的测试,发布版本不在调试器下,根据4.0编译为任何cpu,并在64位Windows 7上运行: / p>
另一个编辑:糟糕这是一个更好的结果。请参阅代码,了解它的工作原理。
10000000直接引用电话:0.011 s
通过界面拨打10000000电话:0.037 s
10000000事件调用:0.067 s
通过Action< int> :0.035 s
一个事件增加了一个直接的做无事测试,一千万次通话。 474秒[编辑,只有.026现在在一个更好的机器,但仍然大约是双倍]
我除了您希望在短时间内做这么多电话(在这种情况下可能还有更根本的设计问题),您将更加关心设计的正确性,而不是每1000万次通话的半秒钟。
We were having a discussion at the office on how to solve a particular problem and using an event was raised (no pun intended). The response was negative citing misuse and that they can be expensive.
I understand the concerns behind misuse and I know that they are just a special multicast delegate but given a scenario where there is at most one listener why would using an event over a method call be considered "expensive"?
Update:
Just to be clear this is not about any particular implementation this is a more general question about the cost of using an event over a method call.
Test it in your scenario - I would imagine that many, many factors can affect this, especially when we're talking something with such a low relative cost as a method/delegate call.
A quick and simple test with a release build not under a debugger, compiled under 4.0 as "any cpu", and running on 64-bit windows 7:
Another Edit: Oops Here's a better result. See the code for how it's working
10000000 direct reference calls : 0.011 s
10000000 calls through an interface : 0.037 s
10000000 invocations of an event : 0.067 s
10000000 calls through Action<int> : 0.035 s
So in a straight "do nothing test" with ten million calls, an event adds .474 sec [edit, only .026 now on a much better machine, still roughly double however]
I would worry more about correctness of design than half a second every 10 million calls, unless you are expecting to do that many calls in short periods of time (in which case perhaps there is a more fundamental design issue).
这篇关于.net事件的性能影响的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!