Which is faster; using event.Invoke(args)
, or just calling event(args)
. What's the difference? Is one faster or slower than the other; or is it just a matter of preference?
-
1Did you try it yourself? Profile it and see which one performs better?– Lasse V. KarlsenMay 8, 2011 at 14:41
-
There doesn't 'seem' to be any difference when it's just a few clients, but I'm concerned about what might happen when I scale it up. I have to make the decision before I publish it in our new product, when one computer might potentially be dealing with thousands of network connections at once.– bbosakMay 8, 2011 at 14:43
-
It would be nice if someone could explain what the difference is in the way the two methods are implemented.– bbosakMay 8, 2011 at 14:45
4 Answers
Writing someDelegate(...)
is a compiler shorthand for someDelegate.Invoke(...)
.
They both compile to the same IL—a callvirt
instruction to that delegate type's Invoke
method.
The Invoke
method is generated by the compiler for each concrete delegate type.
By contrast, the DynamicInvoke
method, defined on the base Delegate
type, uses reflection to call the delegate and is slow.
Since the introduction of null-conditionals in C# 6.0, Invoke
can be used to simplify thread-safe null-checking of delegates. Where you would previously have to do something like
var handler = event;
if (handler != null)
handler(args);
the combination of ?.
and Invoke
allows you to simply write
event?.Invoke(args)
When you call event(args)
, the C# compiler turns it into an IL call for event.Invoke(args)
. It's the same thing - like using string
or System.String
.
Both ways end up generating exactly the same IL, so there isn't any difference in calling them.
That being said, if you have performance problems, changes like this aren't likely to help you much, if at all.