Why is PLINQ slower than LINQ for this code?

若如初见. 提交于 2019-12-02 03:07:20

It's slightly slower because PLINQ has a certain overhead (threads, scheduling, etc) so you have to pick carefully what you will parallelize. This particular code you're benchmarking isn't really worth parallelizing, you have to parallelize over tasks with significant load, otherwise the overhead will weight more than the benefits of parallelization.

The majority of your execution time here is likely going to be in actually creating the list, via the ToList() method. This will have to perform several memory allocations, resizing the list and so on. You're also not gaining much of a benefit from parallelizing here because the final operation has to be synchronized (you're building a single list on the output).

Try doing something significantly more complex/expensive in the parallel segment, like prime factorization, and increasing the number of iterations to the hundreds of thousands (5000 is a very small number to use when profiling). You should start to see the difference then.

Also make sure that you're profiling in release mode; all too often I see attempts to profile in debug mode, and the results from that will not be accurate.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!