且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如果启用优化将永远JIT内联这个方法?

更新时间:2023-11-10 18:54:40

内联是一个实现的细节JIT的,而不是C#编译器。从埃里克Gunnerson的博客




JIT使用了一些启发式
的决定方法是否应该是
直列。
以下是$ B $的一个表b那些更显著(注释
,这不是穷举):




  • 的方法大于32字节的IL不会被内联。

  • 虚拟功能没有内联。

  • 方法具有复杂流量控制不会在成荫。复杂的
    流量控制是任何流量控制等
    比,如果/然后/ ELSE;在此情况下,
    开关或同时

  • 中的方法包含异常处理块不是
    内联,虽然抛出
    例外方法仍候选为
    内联。

  • 如果任何方法的形式参数是结构,该方法将
    不能被内联。


块引用>

虽然你的方法很短,不是很复杂,所以它可能匹配的启发式,可空< T> 结构所以我猜你的方法是不是内联



作为一个经验法则,如果内联这种方法提高性能,JIT将内联此方法;否则就不会。但是,这是真正的JIT并没有什么,你应该代码的实现细节:




我的仔细考虑这些明确的编码启发式,因为它们可能会在JIT的未来版本中改变。不要妥协方法的正确性试图保证它会被内联


块引用>

编辑:显然不是左右被内联结构的位外的日期;更新的信息可以在万斯莫里森的博客


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");
}

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.