VS的String.Format的ToString() [英] String.Format vs ToString()

查看:225
本文介绍了VS的String.Format的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);



只是为了澄清,我不是什么查询方法做,我与幸福明显,只是如果在这个特定的实施例在一个也许一个性能益处比其他。
我知道通过的String.Format()所提供的文化和格式化的更大的灵活性,但我始终只是'的ToString()'数值运算到他们的价值附加到一个标签,或者在一般的基于文本的属性

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.

对于我来说,的String.Format()选项好像这里没有额外的好处多打字,但我不知道是否有任何其他的引擎盖下的利益。处事的一种方式相较于其他

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.

推荐答案

我做Linqpad有点风向标:

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


ToString() 157

格式
264

Format 264

的ToString()看起来一致更快。

ToString() looks consistently faster.

编辑:我要指出的是,我的电脑10万美元的格式的操作只用了2.2秒。这看起来非常像一个微型优化,除非你在做什么是非常关键性能,或迭代 - 这倒是不担心这一点太

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.

这篇关于VS的String.Format的ToString()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆