Jerry Nixon on Windows: Using ToString() to Format

Jerry Nixon on Windows

Tuesday, April 25, 2006

Using ToString() to Format

I found this in the comments area of another blog:

When formatting value types, calling the value types ToString method is more efficient than passing it to String.Format. You avoid a boxing operation. For example:
Double testDouble = 19.95;
String testString1 = String.Format("{0:C}", testDouble); // Boxing operation required.
String testString2 = testDouble.ToString("C"); // No boxing operation required.

In the first version, testDouble gets boxed on the managed heap, the new reference type is passed to String.Format, and garbage collection is required.

In the second version, no boxing occurs, the value type on the stack is used, no garbage collection is required, and your IL code is smaller.