In article String concatenation and int indirect cast it was shown how the ToString() can be used to improve the performance of a program by eliminating the need for the boxing concept. However, the ToString() can still hinder the performance especially when used multiple times to convert a data type or object into a string when the value has not changed. The performance degradation occurs as each time the ToString() is called a new string instance is created.
Let’s run a couple of scenarios to illustrate how the ToString() effects a program
Test Scenario 1:
First let’s determine what the compiler will produce if the ToString() is called twice on the same variable without modifying the variable contents.
int x = 10;
Console.WriteLine(x.ToString() + x.ToString());
ldc.i4.s 10
stloc.0
ldloca.s x
call instance string [mscorlib]System.Int32::ToString()
ldloca.s x
call instance string [mscorlib]System.Int32::ToString()
call string [mscorlib]System.String::Concat(string, string)
call void [mscorlib]System.Console::WriteLine(string)
Test Scenario 2:
Now a variable containing the string value of the variable is created. When verifying the MSIL code generated by the modification, only one string instance is used.
string xStr = x.ToString();
Console.WriteLine(xStr + xStr);
ldc.i4.s 10
stloc.0
ldloca.s x
call instance string [mscorlib]System.Int32::ToString()
stloc.1
ldloc.1
ldloc.1
call string [mscorlib]System.String::Concat(string, string)
call void [mscorlib]System.Console::WriteLine(string)
Important Note
It is important to keep in mind that when a variable is changing between two calls of the ToString() one cannot have just one string representation of the variable contents. When the ToString() method is called a new string representation of the variable instance is created which is separate from the original instance itself. Therefore when the value is expected to change between two consecutive calls to the ToString() it is important to call the ToString() method again to reflect the changes.