Does C# Compiler calculate math on constants?

断了今生、忘了曾经 提交于 2019-12-30 08:13:31

问题


Given the following code:

const int constA = 10;
const int constB = 10;

function GetX(int input) {
    int x = constA * constB * input;
    ...
    return x;
}

Will the .Net compiler 'replace' the expression and put 1000 so the calculation won't be repeated over and over?

In what siutation will the code run fastest:

  1. int x = constA * constB * input;
    
  2. int x = 10 * 10 * input;
    
  3. int x = 100 * input;
    

I guess option 3 will be the faster then 2 but sometimes not the most readable option. Does the compiler recognize patterns like this and optimize it accordingly?


回答1:


C# Constant Expressions:

Whenever an expression is of one of the types listed above and contains only the constructs listed above, the expression is evaluated at compile-time. This is true even if the expression is a sub-expression of a larger expression that contains non-constant constructs.

(and much more to read, if you want to) The "above" referred to is a bulleted list, including:

  • References to const members of class and struct types.

and,

  • The predefined +, –, *, /, %, <<, >>, &, |, ^, &&, ||, ==, !=, <, >, <=, and >= binary operators, provided each operand is of a type listed above.

So, to directly answer your question, yes, the compiler will perform the calculation at compile time.




回答2:


I tried this in LINQPad:

const int constA = 2;
const int constB = 50;

void Main()
{

    Console.WriteLine(GetX(12));
}

int GetX(int input) 
{
    int x = constA * constB * input;

    return x;
}

The IL is :

The hex 64 value (100 in decimal) is the result of the multiplication of the constants. The mul operation is the multiplication by input.

So it sounds like the operations applied to the constants are optimized by the compiler.



来源:https://stackoverflow.com/questions/14752559/does-c-sharp-compiler-calculate-math-on-constants

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