Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

c# - String concatenation with or without .ToString()?

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();
    /* ... */
}

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

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.

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

So for example:

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

is compiled into:

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...