Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C# Compiler calculate math on 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 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?

like image 380
amaters Avatar asked Feb 07 '13 13:02

amaters


2 Answers

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.

like image 198
Damien_The_Unbeliever Avatar answered Sep 25 '22 13:09

Damien_The_Unbeliever


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 :

enter image description here

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.

like image 27
Larry Avatar answered Sep 25 '22 13:09

Larry