
ToString can be used in many ways. There are many different ways of creating the required string. And while it may be tempting to use concatenations, you can achieve better performance by combining the entire format string and generating it all at once.

To begin, we look at a program text written in the C# language that compares two methods of formulating a format string. The required string ends in the letters "MB", indicating megabytes. The Method1 version of the algorithm uses a single format string; the Method2 version uses a format string and then another concatenation after that. The results of the program are that the single format string (Method1) is somewhat faster to execute. This is likely because of less memory pressure due to fewer allocations.
This C# example program tests the performance of ToString. It shows an optimization.
Program that uses ToString method format string [C#]
using System;
using System.Diagnostics;
class Program
{
static string Method1()
{
// Use a format string to create the complete string.
return 100.ToString("0.0 MB");
}
static string Method2()
{
// Use a format string and then concatenate.
return 100.ToString("0.0") + " MB";
}
const int _max = 1000000;
static void Main()
{
var s1 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
Method1();
}
s1.Stop();
var s2 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
Method2();
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000 * 1000) /
_max).ToString("0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000 * 1000) /
_max).ToString("0.00 ns"));
Console.Read();
}
}
Output
228.05 ns
241.35 nsResults. We see, then, that the Method1 version was faster than the Method2 version—with both having the same output. The Method1 version was about 5% faster to execute, and probably incurred less string copying and garbage collection activity during its runtime. Basically, the more complete format string reduces the complexity of the operation from the perspective of the runtime, if not to the programmer.

We showed how you can use more complete format strings in the ToString method to achieve measurable performance gains. And while this sort of optimization is not dramatic in its effects, it signifies a high-quality design and a good understanding of the runtime system and compiler design. At its core, this knowledge speaks to the more fundamental issues related to program design, those at levels that may not be readily apparent but must be understood.
String Type