开发者

Is ToString() optimized by compiler?

开发者 https://www.devze.com 2023-01-02 05:04 出处:网络
Suppose I\'ve following Code: Console.WriteLine(\"Value1: \" + SomeEnum.Value1.ToString() + \"\\r\\nValue2: \" +

Suppose I've following Code:

Console.WriteLine("Value1: " + SomeEnum.Value1.ToString() + "\r\nValue2: " + 
                    SomeOtherEnum.Value2.ToString());

Will Compiler Optimize this to:

Console.WriteLine("Value1: " + SomeEnum.开发者_Python百科Value1 + "\r\nValue2: " +
                         SomeOtherEnum.Value2);

I've checked it with IL Disassembler and there are calls to IL_005a: callvirt instance string [mscorlib]System.Object::ToString()

I don't know if JIT optimizes this.


No, it's the other way around. This:

Console.WriteLine("Value1: " + SomeEnum.Value1 + "\r\nValue2: " +
                     SomeOtherEnum.Value2);

Is translated by the compiler into (the equivalent of) this:

string s = String.Concat("Value1: ", SomeEnum.Value1.ToString(), "\r\n Value2: ", SomeOtherEnum.Value2.ToString());
Console.WriteLine(s);

In both case, the same IL is generated. If you're asking whether the JIT turns that into:

string s = String.Concat("Value1: ", "Value1", "\r\n Value2: ", "Value2");
Console.WriteLine(s);

Then the answer is no. Though I wonder why that would be a problem for you?

0

精彩评论

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