Reputation: 37
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.
Upvotes: -1
Views: 244
Reputation: 4259
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, ...
Upvotes: 1