-1

I have a code (C# .Net 3.5) that looks like that:

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. 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.

yossi
  • 37
  • 6
  • 1
    Why do you have the same code twice? (And it would really help if you'd write *real* code rather than pseudo-code missing semi-colons etc). – Jon Skeet Apr 13 '14 at 15:13
  • So is your question basically, '*How do I efficiently generate many strings with some pattern like `BlaXSomeStringY.Z`?*' – p.s.w.g Apr 13 '14 at 15:16
  • Your code is not very clear as it is clearly not your real code. But one question comes to mind anyway: Why do you create any strings at all?? Just add the expressions to the Lists! Other than that and as a general rule: Using `StringBuilder` will usually be the choice with the best performance, if there is a performance problem.. – TaW Apr 13 '14 at 15:22
  • 1
    unless your n is huge you wont notice any significant performance difference. I would use whatever makes your code most readable. – thumbmunkeys Apr 13 '14 at 15:23
  • 3
    If you want to know which of two things is faster then **write it both ways and try it**. Then you'll know. – Eric Lippert Apr 13 '14 at 15:44
  • No, StringBuilder will not improve this code, it is already optimal. – Hans Passant Apr 13 '14 at 15:44

1 Answers1

1

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, ...

pero
  • 4,169
  • 26
  • 27
  • Thanks Peter. Actually "somestringX" and "blaY" are defined in consts. So I cant write "SomestringXBlaY" Will it still improve the performence? – yossi Apr 15 '14 at 10:04