var strings = new List<string>();
var result = new List<string>();
for (int i = 0; i < 10000; i++)
{
strings.Add(i.ToString());
}
var sw = new Stopwatch();
sw.Start();
for (int i = 0; i < strings.Count; i++)
{
strings[i] += strings[i];
}
sw.Stop();
Console.WriteLine(sw.ElapsedTicks); //1319
sw.Restart();
ParallelLoopResult loopResult = Parallel.ForEach(
Partitioner.Create(strings, true),
() => new List<string>(),
(str, state, i, listLocal) =>
{
listLocal.Add(str);
return listLocal;
},
o =>
{
lock (result)
result.AddRange(o);
});
sw.Stop();
Console.WriteLine(sw.ElapsedTicks); //5679
//为什么用并行后效率差了将近5倍?
并行这样玩当然没优势了,List的操作不还得排队啊~如果要并行,应该选择耗时的任务来测试。
开线程的代价也是不容忽视的,而且你还有lock,不待你这样玩的。。。