Recommendation 88: Parallelism is not always faster
Parallel to the background tasks and task management, will bring some overhead, if a job can be completed quickly, or the loop body is small, then the speed of parallel may be slower than non-parallel.
Looking at this example, we compare the time consumption in both synchronous and parallel states:
Static voidMain (string[] args) {Stopwatch Watch=NewStopwatch (); Watch. Start (); Doinfor (); Watch. Stop (); Console.WriteLine ("Synchronization time: {0}", watch. Elapsed); Watch. Restart (); Doinparallefor (); Watch. Stop (); Console.WriteLine ("Parallel time consuming: {0}", watch. Elapsed); Console.readkey (); } Static voiddosomething () { for(inti =0; I <Ten; i++) {i++; } } Static voiddoinfor () { for(inti =0; I < $; i++) {dosomething (); } } Static voiddoinparallefor () {Parallel.For (0, $, (i) = ={dosomething (); }); }
The above code in the author's current dual-core PC output is:
Synchronization time: 00:00:00.0005583
Concurrent Time: 00:00:00.0033604
It can be seen that synchronization took only 0.55 milliseconds, while parallelism used 3.3 milliseconds to complete the work.
Now, to simulate getting the loop body to do more, change the loop body in the DoSomething method from 10 to 10000000. The result of the operation is:
Synchronization time: 00:00:01.3059138
Concurrent Time: 00:00:00.6560593
When the loop body needs to do more work, we find that synchronization takes 1.3 seconds to complete the work, while in parallel the work is done in only 0.6 seconds.
Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia
157 recommendations for writing high-quality code to improve C # programs--recommendation 88: Parallelism is not always faster