Speed of events.

wyrd

Senior Contributor
Joined
Aug 23, 2002
Messages
1,405
Location
California
Does anyone know the speed of an event compared to a simple method call? Is it significantly slower?
 
Last edited:
When an event fires, the handler sub is called just like if you called it. Shouldn't be any different.
 
Yeah but events are implemented with delegates. I was under the impression that delegates are quite slow (at least that's what I remember from an MSDN article I read.. I'll have to dig it up)
 
Here we are;

http://msdn.microsoft.com/library/?url=/library/en-us/dndotnet/html/fastmanagedcode.asp

All of these rich semantics are not inexpensive. Comparing Table 10 and Table 3, note that delegate invoke is approximately eight times slower than a method call. Expect that to improve over time.

So.. to reword my question; Events are implemented using delegates, so that would mean events are eight times slower then method calls?

For some reason I don't think that I'm fully understanding something here, which is the reason for my question.
 
The code isn't 8 times slower - just the overheads of invoking the call. If a function took 8 seconds to run then using the articles figures a delegate would incur 30 or 40 nanoseconds extra overhead .
The overall time to execute would be the same to all intents and purposes.
 
Last edited:
There will definitely be some overhead in events, but generally not of consequence unless you plan on raising hundreds of events (or more) per second. Events can use single or multicase delegates (multiple receivers), so if you have more listeners you will have more overhead (I imagine it working like a foreach that loops through the functions, calling each one in turn).

Again, you could easily test this with a sample project that loops and calls a function x number of times and raises an event the same number. Keep in mind that your function/event handler is likely do *something*, and that the something is likely to take longer than the call. If it's generally a LOT longer, than delegats won't be adding that much in terms of the overall time. If they're very fast events (setting a property or two or just a few if's), then a pure method call might be worth it.

-Ner
 
I'd be calling 100's of events per second. The reason I asked is because I was thinking of designing a game that was event driven. But if there's some overhead involved then it probably isn't worth the performance hit. :( I guess I'll have to program a quick little test app to see just how slow (or fast) events are.
 
Back
Top