开发者

event.Invoke(args) vs event(args). Which is faster?

Which is faster; using e开发者_如何学运维vent.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?


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜