简体   繁体   中英

Is ToString() optimized by compiler?

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.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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM