C # compiler calculates math by constants?

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 that the calculation does not repeat over and over?

In which syntax will the code run faster:

  •  int x = constA * constB * input; 
  •  int x = 10 * 10 * input; 
  •  int x = 100 * input; 

I think option 3 will be faster than 2, but sometimes not the most readable one. Does the compiler recognize such patterns and optimize it accordingly?

+8
performance compiler-optimization c # constants
source share
2 answers

C # Constant Expressions :

Whenever an expression is 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 subexpression of a larger expression containing inconsistent constructs.

(and much more to read if you want). “above” is a bulleted list, including:

  • References to constant elements of classes and types.

and

  • The predefined +, -, *, /,%, <, →, &, |, ^, &, ||, == ,! =, <,>, <; =, and> = binary operators if each operand is of the type specified above.

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

+13
source share

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

IL:

enter image description here

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

So, it seems that the operations applied to constants are optimized by the compiler.

+7
source share

All Articles