Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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");
}
like image 440
ChaosPandion Avatar asked Aug 27 '09 18:08

ChaosPandion


1 Answers

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.

like image 71
dtb Avatar answered Oct 18 '22 16:10

dtb