开发者

.NET String performance question

开发者 https://www.devze.com 2022-12-13 16:33 出处:网络
Is it better, from a performance standpoint, to use \"Example1\"?I\'m assuming that \"Example2\" would create a new string开发者_高级运维 on the heap in each iteration while \"Example1\" would not...

Is it better, from a performance standpoint, to use "Example1"? I'm assuming that "Example2" would create a new string开发者_高级运维 on the heap in each iteration while "Example1" would not...

Example1:

StringBuilder letsCount = new StringBuilder("Let's count! ");
string sep = ", ";
for(int i=; i< 100; i++)
{
     letsCount.Append(i + sep);
}

Example2:

StringBuilder letsCount = new StringBuilder("Let's count! ");
for(int i=; i< 100; i++)
{
     letsCount.Append(i + ", ");
}


The .NET CLR is much smarter than that. It "interns" string literals so that there is only one instance.

It's also worth noting that if you were truly concerned about string concatenation, you would want to turn the single Append call into two append calls. The reality, however, is that the overhead of two calls probably outweighs any minor concatenation cost. In either case, it's probably nearly immeasurable except in very controlled conditions.


They are identical.


Actually a much faster way to do it would be

string letsCount = "Let's count! ";
string[] numbers = new string[100];
for(int i=0; i< 100; i++)
{ 
   numbers[i]=i+", ";
}
String.Join(letsCount, numbers);

See here

0

精彩评论

暂无评论...
验证码 换一张
取 消