请问C#编译器在计算数学常数? [英] Does C# Compiler calculate math on constants?
问题描述
由于下面的代码:
const int constA = 10;
const int constB = 10;
function GetX(int input) {
int x = constA * constB * input;
...
return x;
}
请问.net编译器'取代'的表达,并把1000这样的计算?不会重复一遍又一遍
Will the .Net compiler 'replace' the expression and put 1000 so the calculation won't be repeated over and over?
在什么siutation将代码运行速度最快的:
In what siutation will the code run fastest:
int x = constA * constB * input;
int x = 10 * 10 * input;
int x = 100 * input;
我猜选项3将是更快然后2,但有时候不是最可读的选项。该编译器识别这样的模式,并据此优化呢?
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#常量表达式:
只要表达式是上面列出的类型之一,并且只包含上面列出的构建体,所述表达是在编译时进行评价。这是真实的,即使该表达式是一个包含非恒定构建一个更大的表达式的子表达式。
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:
- 对类和结构类型的常量成员。
和
- 预定义的+, ;&放;, ||,==,=,<,>,<!=和> =二元运算符,提供的每个操作数是上面列出的类型
所以,直接回答你的问题,是的,编译器会在编译时进行计算。
So, to directly answer your question, yes, the compiler will perform the calculation at compile time.
这篇关于请问C#编译器在计算数学常数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!