String.Format vs ToString()

女生的网名这么多〃 提交于 2019-12-03 23:53:55

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.

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.

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

ToString is the default representation of an object.

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.

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 features of Format().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!