开发者

Calculated Constants in C#

开发者 https://www.devze.com 2023-02-18 14:33 出处:网络
Good morning, afternoon or night, Will either the MSIL or the JIT compiler replace things like 1 << 5 o开发者_Go百科r 1 << 31 in the code with 32 and 2147483648, respectively, or will the

Good morning, afternoon or night,

Will either the MSIL or the JIT compiler replace things like 1 << 5 o开发者_Go百科r 1 << 31 in the code with 32 and 2147483648, respectively, or will they wait for method execution to evaluate those constants "just in time" since they involve other methods (operators)?

Thank you very much.


Try it.

The following code

    static void Main ( string[] args )
    {
        Console.WriteLine ( 1 << 4 );
    }

Gets compiled to

  IL_0000:  nop
  IL_0001:  ldc.i4.s   16
  IL_0003:  call       void [mscorlib]System.Console::WriteLine(int32)
  IL_0008:  nop
  IL_0009:  ret

It just loads the constant 16 and passes it to WriteLine.


Yes. Look at the compiled IL for a program that just does Console.WriteLine(1 << 5) and you'll see it's the same as that for Console.WriteLine(32) or Console.WriteLine(0x20). The same applies for plenty of other such constants.


(Tested) - They do in fact result in the same computed value after compilation, the C# spec confirms:

10.4 Constants

A constant is a class member that represents a constant value: a value that can be computed at compile-time. A constant-declaration introduces one or more constants of a given type.

0

精彩评论

暂无评论...
验证码 换一张
取 消