重复访问器调用的编译器优化 [英] Compiler optimization of repeated accessor calls

查看:95
本文介绍了重复访问器调用的编译器优化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近发现,对于某些类型的财务计算,以下模式更易于遵循和测试,尤其是在我们可能需要从计算的各个阶段获取数字的情况下.

I've found recently that for some types of financial calculations that the following pattern is much easier to follow and test especially in situations where we may need to get numbers from various stages of the computation.

public class nonsensical_calculator
{ 

   ...

    double _rate;
    int _term;
    int _days;

    double monthlyRate { get { return _rate / 12; }}

    public double days { get { return (1 - i); }}
    double ar   { get { return (1+ days) /(monthlyRate  * days)
    double bleh { get { return Math.Pow(ar - days, _term)
    public double raar { get { return bleh * ar/2 * ar / days; }}
    ....
}

显然,这通常会导致给定公式中对同一访问器的多次调用.我很好奇编译器是否足够聪明,可以优化这些重复的调用而不会造成状态的中间变化,或者这种样式是否会导致性能下降.

Obviously this often results in multiple calls to the same accessor within a given formula. I was curious as to whether or not the compiler is smart enough to optimize away these repeated calls with no intervening change in state, or whether this style is causing a decent performance hit.

更多的阅读建议总是值得赞赏的

Further reading suggestions are always appreciated

推荐答案

据我所知,C#编译器不会对此进行优化,因为它无法确定副作用(例如,如果您在吸气剂中有accessCount++怎么办?)请在此处查看

From what I know, the C# compiler doesn't optimize this, because it can't be certain of side-effects (e.g. what if you have accessCount++ in the getter?) Take a look here at an excellent answer by Eric Lippert

从该答案开始:

C#编译器从不进行这种优化.如前所述,这样做将要求编译器查看正在调用的代码,并验证其计算的结果在被调用者的代码生命周期内不会发生变化. C#编译器不这样做.

The C# compiler never ever does this sort of optimization; as noted, doing so would require that the compiler peer into the code being called and verify that the result it computes does not change over the lifetime of the callee's code. The C# compiler does not do so.

JIT编译器可能会.没有理由不能这样做.它所有的代码都放在那儿.内联属性获取器是完全免费的,如果抖动确定内联属性获取器返回的值可以缓存在寄存器中并重新使用,则可以这样做. (如果您不希望这样做,因为可以在另一个线程上修改该值,则说明您已经有一个竞争条件错误;请在担心性能之前修复该错误.)

The JIT compiler might. No reason why it couldn't. It has all the code sitting right there. It is completely free to inline the property getter, and if the jitter determines that the inlined property getter returns a value that can be cached in a register and re-used, then it is free to do so. (If you don't want it to do so because the value could be modified on another thread then you already have a race condition bug; fix the bug before you worry about performance.)

请注意,就像C#编译器团队中的Eric一样,我相信他的回答:)

Just a note, seeing as Eric's on the C# compiler team, I trust his answer :)

这篇关于重复访问器调用的编译器优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆