开发者

How expensive are method calls in .net

What is the relative performance cost of calling a 开发者_StackOverflowmethod over in-line code?


That will depend on many things

  • Whether the JIT inlines it for you
  • Whether it's virtual
  • The number and size of parameters
  • Whether it's an instance method (with the implicit nullity check)
  • Whether there's a return value (and its size if so)

It's very, very unlikely to be your bottleneck though. As always, write the most readable code you can first, and then benchmark it to see whether it performs well enough. If it doesn't, use a profiler to find the hotspots which may be worth micro-optimising.


There is a cost associated with method calls;

Arguments need to be pushed on the stack or stored in registers, the method prolog and epilog need to be executed and so on. The cost of these calls can be avoided by In-lining.

But, JIT uses a number of heuristics to decide whether a method should be in-lined. Following factors influence JIT, not to In-line a method.

  • Methods that are greater than 32 bytes of IL
  • Virtual functions
  • Methods that have complex flow control
  • Methods that contain exception-handling blocks
  • If any of the method's formal arguments are structs

Reference: Method Inlining


Same as in C++. Basically a call and a return, plus setting up parameters. Note, though, that the JIT can inline method calls - so it may not be as expensive in a particular context as you think.


The performance cost is so inconsequential as to be irrelevant in comparison to making the code easy to read and its intent clear.


Insignificant. Every call in .net, at least for C# is virtual call even if method is not marked virtual, consider it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜