字符串连接带或不带的ToString()? [英] String concatenation with or without .ToString()?

查看:99
本文介绍了字符串连接带或不带的ToString()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个string类型以下面的方式分配语句:

I have a statement where a string is assigned in the following manner:

for (int i = 0; i < x; i++) 
{
    Foo.MyStringProperty = "Bar_" + i.ToString();
    /* ... */
}

是否有()或只是简单的 i.ToString任何性能上的差异,因为两者都只是转换到(文化不变?)等效字符串?

Are there any performance differences between i.ToString() or just plain i, as both are just converted to the (culture invariant?) string equivalent?

我深知 String.Concat()的存在的String.Format 的StringBuilder 等,但为求这种情况下,让我们假设我只可以使用 + 连接。

I am well aware of the existence of String.Concat(), String.Format, StringBuilder, etc., but for the sake of this case, lets assume I may only use + concatenation.

在此先感谢。

推荐答案

+ 串联使用 String.Concat 反正 - 字符串本身不公开+运营商

+ concatenation uses String.Concat anyway - String itself doesn't expose a + operator.

因此​​,例如:

int i = 10;
string x = "hello" + i;

被编译为:

int i = 10;
object o1 = "hello";
object o2 = i; // Note boxing
string x = string.Concat(o1, o2);

而调用的ToString 将直接避免装箱并调用 CONCAT(字符串,字符串)超载。因此,使用的ToString 调用的版本将的的更有效率 - 但我高度怀疑,这将是显著的,我会强烈呼吁你去与任何版本中,你感受到的是更具有可读性。

Whereas calling ToString directly will avoid boxing and call the Concat(string, string) overload. Therefore the version with the ToString call will be slightly more efficient - but I highly doubt that it'll be significant, and I'd strongly urge you to go with whichever version you feel is more readable.

这篇关于字符串连接带或不带的ToString()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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