C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
There are many different ways of creating the required string. It is tempting to use concatenations. But you can achieve better performance by combining the entire format string.
Example. To begin, we look at a program 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.
Note: Method1 is likely faster because of less memory pressure due to fewer allocations.
C# program that uses ToString method, format string 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 ns
We see that the Method1 version was faster than the Method2 version. The Method1 version was about 5% faster to execute, and probably incurred less string copying and garbage collection activity during its runtime.
Note: The complete format string reduces the complexity of the operation from the perspective of the runtime, if not to the programmer.
Summary. We can use more complete format strings in the ToString method to achieve measurable performance gains. This optimization is not dramatic in its effects. But it signifies a good understanding of the runtime system and compiler design.