您可以使用收到的建议(例如使用 StringBuilder)并使用 Parallel 扩展,使用您机器中的内核数量来并行完成工作。
看看这段代码:
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();
}
}
看看我的笔记本(AMD Turion64 X2 - 2 cores)上运行的一些措施:
正常循环时间:00:00:03.5956428
并行时间:00:00:01.8707367
正常循环时间:00:00:02.1467821
并行时间:00:00:01.4627365
正常循环时间:00:00:03.4123084
并行时间:00:00:01.6704408
希望这会有所帮助。
里卡多·拉塞尔达·布兰科堡