Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.Format vs ToString()

Can anyone explain if there is any benefit in either one of the following methods:

decimal d = 12.0m;

// 1. how I'd have done it
myLabel.Text = d.ToString();

// 2. how I saw someone do it today
myLabel.Text = String.Format("{0}", d);

Just to clarify, I'm not querying what the methods do, I'm obviously happy with that, just if there is perhaps a performance benefit in one over the other in this specific example. I'm aware of the added flexibility of cultures and formatting offered by string.format(), but I'd always just 'tostring()' numerics to attach their value to a label, or text based property in general.

To me, the string.format() option seems like more typing for no additional benefit here, but I wondered if there are any other 'under the hood' benefits of doing things one way vs the other.

like image 502
dougajmcdonald Avatar asked May 01 '12 15:05

dougajmcdonald


People also ask

What is ToString () and string format ()?

A toString() is an in-built method in Java that returns the value given to it in string format. Hence, any object that this method is applied on, will then be returned as a string object.

What is the difference between ToString () and convert ToString ()?

ToString method displays a blank line but output using ToString method throws an un-handled exception. Convert. ToString handles null while ToString doesn't and throws a NULL reference exception.

What is string format in Java?

In java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string.


1 Answers

I did a little benchmark in Linqpad:

void Main()
{
    int iterations = 1000000;
    decimal d = 12.0m;
    var text = "";

    var sw = Stopwatch.StartNew();
    for (int i = 0; i < iterations; i++)
    {
        // 1. how I'd have done it
        text = d.ToString();
    }
    sw.Stop();
    sw.ElapsedMilliseconds.Dump("ToString()");

    sw = Stopwatch.StartNew();
    for (int i = 0; i < iterations; i++)
    {
        // 2. how I saw someone do it today
        text = String.Format("{0}", d);
    }
    sw.Stop();
    sw.ElapsedMilliseconds.Dump("Format");
}

ToString() 157

Format 264

ToString() looks consistently faster.

EDIT: I should point out, that on my PC 10 million "Format" operations only took 2.2 seconds. This looks very much like a micro-optimization, and unless what you're doing is extremely performance-critical, or iterative - it'd not worry about this too much.

like image 138
Dave Bish Avatar answered Sep 16 '22 16:09

Dave Bish