字符串连接带或不带的ToString()?不带、字符串、ToString

2023-09-03 01:15:28 作者:别爱我、会上瘾

我有一个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.