简体   繁体   English

我应该使用 StringBuilder 吗?

[英]Should I use StringBuilder?

I have a code (C# .Net 3.5) that looks like that:我有一个看起来像这样的代码(C# .Net 3.5):

string s1, s2;

for (i=0; i<n; i++)
{
  s1 = "SomeString1"
  s2 = s1 + '.' + i
  SomeList.Add("Bla1" + s2);

  s1 = "SomeString2"
  s2 = s1 + '.' + i
  SomeList("Bla1" + s2);

  s1 = "SomeString3"
  s2 = s1 + '.' + i
  SomeList.Add("Bla1" + s2);
 .
 .
 .
 etc.....
}

for (i=0; i<n; i++)
{
  s1 = "SomeString1"
  s2 = s1 + '.' + i
  SomeList.Add("Bla2" + s2);

  s1 = "SomeString2"
  s2 = s1 + '.' + i
  SomeList("Bla2" + s2);

  s1 = "SomeString3"
  s2 = s1 + '.' + i
  SomeList.Add("Bla2" + s2);
 .
 .
 .
 etc.....
}
.
.
.
etc...

n in not so big (around 5), and this pattern repeats for about 20 times. n 不是很大(大约 5),并且这种模式重复了大约 20 次。 This happens in the beginning of my program and I want the startup to be faster.这发生在我的程序开始时,我希望启动速度更快。 The question is: Is there a better way to do that (more efficient)?问题是:有没有更好的方法来做到这一点(更有效)? Should I use string builder instead of creating new strings over and over?我应该使用字符串生成器而不是一遍又一遍地创建新字符串吗? Will it help, or the "replace" actions will take as much time?它会有所帮助,还是“替换”操作将花费同样多的时间?

Thanks, Yossi.谢谢,约西。

Change:改变:

s1 = "SomeString1"
s2 = s1 + '.' + i
SomeList.Add("Bla2" + s2);

To:到:

SomeList.Add(string.Format("Bla2SomeString1.{0}", i));

That way you will reduce number of string allocations, concatenations, ...这样,您将减少字符串分配、连接、...的数量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM