Click here to Skip to main content
15,881,757 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Which loop is faster ???

1st Loop (Traditional)


C#
List<string> Days = new List<string>();
                for (int i = 1; i <= 31; i++)
                {
                    Days.Add(i.ToString("00"));
                }


Or 2nd Parallel for loop:

C#
List<string> Days = new List<string>();
System.Threading.Tasks.Parallel.For(1, 31, i =>
                {
                    Days.Add(i.ToString("00"));
                });




Thanks
Posted
Comments
Mehdi Gholam 26-Feb-15 0:21am    
Try and see.
deepakdynamite 26-Feb-15 0:47am    
Ahaaa !!! Thanks for your precious answer...

You can find valuable peice of information from this Disappointing performance with Parallel.For[^]
 
Share this answer
 
Comments
Maciej Los 26-Feb-15 1:57am    
+5!
Solution 1 by _Asif_[^] is very good, even if does not contain exact answer.

Traditional for loop is faster than Parrarel loop and even Linq method too:

C#
List<string> Days = Enumerable.Range(1,31).Select(x=>x.ToString("00")).ToList();


Time of execution:
1) traditional:  00:00.070 s
2) parrarel:     00:00.197 s
3) linq:         00:00.330 s
 
Share this answer
 
v2
Comments
Mehdi Gholam 26-Feb-15 3:47am    
5'ed
Maciej Los 26-Feb-15 3:52am    
Thank you, Mehdi ;)
deepakdynamite 26-Feb-15 5:27am    
Thanks. It would be great if you can share how you got these statistical figures ??
Maciej Los 26-Feb-15 6:06am    
I'm using LinqPad, which has got such of functionality ;)
deepakdynamite 26-Feb-15 23:15pm    
Thanks alot ...
The loop can't be parallelized to start with, since Days.Add() requires sequential processing. Therefore parallel.for just adds overhead without improving performance.

The key thing to look for is whether there is a variable that gets modified with each execution.

In this case, Days is changed with each execution, and mixing the order of execution will mix up the order of elements in the final list.

P.S.: I just realized this assessment isn't entirely correct. I've only considered the command Days.Add() without considering the command embedded with the function parameter: i.ToString(). The later can be parallelized, as it doesn't depend on the order of processing. However, if you don't immediately store the string in the list, the overhead of creating an additional temporary string probably outweighs the benefit of parallelizing the string conversion. So it isn't as clear cut as I outlined it above.
 
Share this answer
 
v2
Comments
Maciej Los 26-Feb-15 6:07am    
Good catch!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900