TheVillageIdiot
TheVillageIdiot

Reputation: 40517

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.

Upvotes: 3

Views: 197

Answers (1)

Dean Harding
Dean Harding

Reputation: 72668

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?

Upvotes: 3

Related Questions