String.Format vs ToString()
Asked Answered
W

5

18

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.

Wainscot answered 1/5, 2012 at 15:40 Comment(1)
If you are not sure is it null, use Format instead.Kinghorn
F
29

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.

Faggot answered 1/5, 2012 at 15:46 Comment(3)
This would have been my expectation, and it does appear to confirm what others have said about the inner workings of String.Format() (ie using a Builder), thanks for the results.Wainscot
I added Convert.ToString(d); into the mix and my numbers were: ToString() -> 220 Format -> 454 Convert.ToString() -> 224Quadruped
I did actual benchmarks and confirmed this independently in an ASP.Net C# web application. Using ToString and the '+' operator was about 2x faster than using String.Format. String.Format has to do much more sophisticated parsing of the format string. Such small improvements add up and can make a difference in a web page where each millisecond of load time counts. In terms of priorities though, this particular optimization is typically not on a critical path.Stale
A
4

string format - uses under the hood- StringBuilder - which is much faster for working with strings.

ToString is the default representation of an object.

Annabellannabella answered 1/5, 2012 at 15:44 Comment(1)
Yeah I appreciate the concepts, but with the example here, the results are equivalent, hence I was curious if there was anything else to take into account. If String.Format() uses a stringbuilder, it would suggest that is has to call ToString() on itself anyway, and in this example presumably that would be slower than the default ToString() representation of the decimalWainscot
E
4

string.Format can be used for creating other complex strings since it can take a params argument set; so this isn't really a question of apples VS apples.

Emelda answered 1/5, 2012 at 15:44 Comment(0)
U
3

ToString() is better, since Format() needs to call ToString() under the hood anyway. If you need to specify custom formatting, Format() offers format specifiers like alignment/padding. Otherwise, there is no reason not to use ToString().

ToString() fits much better into self-documenting code than Format(), and just makes more sense.

Unhallowed answered 1/5, 2012 at 15:44 Comment(1)
This is how I was viewing things, I'm guessing that is what @Royi says above is the case, then as you say, I've got to call ToString() on a stringbuilder by using .Format(), which suggests it's creating a StringBuilder for no reason (in this example).Wainscot
S
1

I would expect there to be a marginal performance benefit of calling ToString() since it doesn't have to parse your format string. That, and it reads much more nicely if you are not using any features of Format().

Schlock answered 1/5, 2012 at 15:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.