开发者

Performance implications of .net Events

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开发者_如何学Go 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).


In .NET 2.0 calling a delegate is just as fast as an interface method call. They even seem to be a bit faster.

But even if the overhead were 10x higher, I doubt delegate calls would ever be the speed bottleneck in your application. Use a profiler if you want to find the real bottlenecks.

edit in response to the claim that events are slower than delegates: In fact, events are delegates. This code shows that their performance is identical, at least on my machine.


Performance is definitely not something you should concern yourself about. You're talking about nanoseconds here. If you have just one listener, there is no difference at all.

I would simply consider what makes more sense in your application, using events or calling a method and choose the best option. The main difference being that an object A generating events doesn't have to know its listener(s). The same object A calling a method has to know the instance to call it from. Where do you want to put the dependency?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜