You can use the advices received (use StringBuilder for example) and with Parallel extensions, use how many cores you have in your machine to do the work in parallel.
Look at this code:
class Program {
static void Main(String[] args) {
// Filling the data
List<KeyValuePair<String, String>> map = new List<KeyValuePair<String, String>>();
List<StringBuilder> strings = new List<StringBuilder>();
List<StringBuilder> strings2 = new List<StringBuilder>();
for (Int32 i = 0; i < 50; i++) {
String key = String.Format("[KEY{0}]", i);
String value = String.Format("Text of KEY{0}", i);
KeyValuePair<String, String> keyValuePair = new KeyValuePair<String, String>(key, value);
map.Add(keyValuePair);
}
for (Int32 i = 0; i < 1024; i++) {
StringBuilder text = new StringBuilder();
foreach (KeyValuePair<String, String> keyValuePair in map) {
text.AppendFormat("Some text before - {0} - Some text after.", keyValuePair.Key);
text.AppendLine();
}
strings.Add(text);
strings2.Add(text);
}
// Measuring the normal loop
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
foreach (StringBuilder text in strings) {
foreach (KeyValuePair<String, String> eachMap in map) {
text.Replace(eachMap.Key, eachMap.Value);
}
}
stopwatch.Stop();
Console.WriteLine("Time with normal loop: {0}", stopwatch.Elapsed);
// Measuring the parallel loop
stopwatch.Reset();
stopwatch.Start();
Parallel.ForEach(strings2, text => {
foreach (KeyValuePair<String, String> eachMap in map) {
text.Replace(eachMap.Key, eachMap.Value);
}
});
stopwatch.Stop();
Console.WriteLine("Time with parallel: {0}", stopwatch.Elapsed);
Console.ReadLine();
}
}
And look at some measures running on my nootebook (AMD Turion64 X2 - 2 cores):
Time with normal loop: 00:00:03.5956428
Time with parallel: 00:00:01.8707367
Time with normal loop: 00:00:02.1467821
Time with parallel: 00:00:01.4627365
Time with normal loop: 00:00:03.4123084
Time with parallel: 00:00:01.6704408
Hope this helps.
Ricardo Lacerda Castelo Branco