Code optimization

后端 未结 3 1622
鱼传尺愫
鱼传尺愫 2021-01-29 16:07

When i\'m trying to optimize my code, I often run into a dilemma:

I have an expression like this:

int x = 5 + y * y;
int z = sqrt(12) + y * y;

3条回答
  •  佛祖请我去吃肉
    2021-01-29 17:06

    One of the older compiler optimisations is "common subexpression elimination" - in this case y * y is such a common subexpression.

    It may still make sense to show a reader of the code that the expression only needs calculating once, but any compiler produced in the last ten years will calculate this perfectly fine without repeating the multiplication.

    Trying to "beat the compiler on it's own game" is often futile, and certainly needs measuring to ensure you get a better result than the compiler. Adding extra variables MAY cause the compiler to produce worse code, because it gets "confused", so it may not help at all.

    And ALWAYS when it comes to performance (or code size) results from varying optimizations, measure, measure again, and measure a third time to make sure you get the results you expect. It's not very easy to predict from looking at code which is faster, and which is slower. But it'd definitely be surprised if y * y is calculated twice even with a low level of optimisation in your compiler.

提交回复
热议问题