views:

83

answers:

1

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.

+3  A: 

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?

Dean Harding
@codeka see my comment on @Jon Seigel's comment
TheVillageIdiot
OK, well anyway, the two lines you posted are basically equivalent. If you have a tool like ReSharper, it actually notifies you when calls to ToString() are redundant. It's not that there's any performance hit, it's just not needed.
Dean Harding