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

前端 未结 4 1314
南旧
南旧 2020-12-13 18:31

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 ju

相关标签:
4条回答
  • 2020-12-13 19:21

    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.

    0 讨论(0)
  • 2020-12-13 19:26

    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 讨论(0)
  • 2020-12-13 19:27

    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)
    
    0 讨论(0)
  • 2020-12-13 19:37

    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.

    0 讨论(0)
提交回复
热议问题