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:
int x = constA * constB * input;
int x = 10 * 10 * input;
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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With