If optimizations are enabled will the JIT always inline this method?

你说的曾经没有我的故事 提交于 2019-12-21 01:06:43

问题


I am not expecting a definite yes or no. Any knowledge you might have I will consider as an answer.

private String CalculateCharge(Nullable<Decimal> bill, Nullable<Decimal> rate)
{
    return ((bill ?? 0.0m) * (rate ?? 0.0m)).ToString("C");
}

回答1:


Inlining is an implementation detail of the JIT, not of the C# compiler. From Eric Gunnerson's blog:

The JIT uses a number of heuristics to decide whether a method should be in-lined. The following is a list of the more significant of those (note that this is not exhaustive):

  • Methods that are greater than 32 bytes of IL will not be inlined.
  • Virtual functions are not inlined.
  • Methods that have complex flow control will not be in-lined. Complex flow control is any flow control other than if/then/else; in this case, switch or while.
  • Methods that contain exception-handling blocks are not inlined, though methods that throw exceptions are still candidates for inlining.
  • If any of the method's formal arguments are structs, the method will not be inlined.

Although your method is quite short and not very complex so it might match the heuristics, Nullable<T> is a struct so I'd guess your method is not inlined.

As a rule of thumb, if inlining this method improves performance, the JIT will inline this method; otherwise it will not. But this is really an implementation detail of the JIT and nothing you should code for:

I would carefully consider explicitly coding for these heuristics because they might change in future versions of the JIT. Don't compromise the correctness of the method to attempt to guarantee that it will be inlined.

EDIT: Apparently the bit about structs not being inlined is out-of-date; updated information can be found at Vance Morrison's blog.



来源:https://stackoverflow.com/questions/1343019/if-optimizations-are-enabled-will-the-jit-always-inline-this-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!