Using ToString() on the same item multiple times

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.

  1. int x = 10;
  2. Console.WriteLine(x.ToString() + x.ToString());
  1. ldc.i4.s   10
  2. stloc.0
  3. ldloca.s   x
  4. call       instance string [mscorlib]System.Int32::ToString()
  5. ldloca.s   x
  6. call       instance string [mscorlib]System.Int32::ToString()
  7. call       string [mscorlib]System.String::Concat(string, string)
  8. 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.

  1. string xStr = x.ToString();
  2. Console.WriteLine(xStr + xStr);
  1. ldc.i4.s   10
  2. stloc.0
  3. ldloca.s   x
  4. call       instance string [mscorlib]System.Int32::ToString()
  5. stloc.1
  6. ldloc.1
  7. ldloc.1
  8. call       string [mscorlib]System.String::Concat(string, string)
  9. 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.