.NET Kombat (Format vs. ToString)

In converting some legacy VB6 code to VB.NET, I noticed that there was a lot of use of the Format function in the code to convert numbers to strings. This makes sense as Format was pretty much the only game in town in VB6.

However, in .NET, they introduced a handy-dandy .ToString() method that, on the surface, seems to do much the same thing as the Format function. I have been able to use them pretty much interchangeably with the desired results coming out every time.

I started to wonder which way was faster. Since I am a big proponent of empirical knowledge instead of just trying to get the theoretical story behind the two ways to do this, I rolled together this quick VB.NET console application:

Imports System.Text
 
Module Module1
 
    Sub Main()
 
        Dim i As Integer
        Dim r As Random = New Random()
        Dim t As Double
 
        System.Console.WriteLine("10,000,000 Formats")
        Dim sb1 As New stringbuilder
        t = Timer
        For i = 1 To 10000000
            sb1.Append(Format(r.NextDouble * 100.0, "###0.00 "))
        Next
        System.Console.WriteLine("Seconds elapsed: " + (Timer - t).ToString("#######0.00"))
        System.Console.WriteLine("Length of string builder: " + sb1.Length.ToString())
        System.Console.WriteLine()
 
        System.Console.WriteLine("10,000,000 ToStrings")
        Dim sb2 As New StringBuilder
        t = Timer
        For i = 1 To 10000000
            sb2.Append((r.NextDouble * 100.0).ToString("###0.00 "))
        Next
        System.Console.WriteLine("Seconds elapsed: " + (Timer - t).ToString("#######0.00"))
        System.Console.WriteLine("Length of string builder: " + sb2.Length.ToString())
        System.Console.WriteLine()
 
        System.Console.WriteLine("Press any key to end the program ")
        System.Console.ReadKey()
 
    End Sub
 
End Module

And here are the results:

As you can see, the ToString method is about 15% faster when doing 10 million calls with random numbers.

Oh, and by the way, Happy Pancake Day.

Leave a Reply