|
||||||
| News Programming news and events. |
![]() |
|
|
LinkBack | Thread Tools | Search this Thread | Display Modes |
|
|||
The foreach syntax sugar is a blessing and for many complex loops it is not worth transforming foreach into for. But for certain kind of loops, like short loops made of one or two instructions nested in some other loops, these 5 times factor can become a huge bonus. And the good news is that the code of NDepend has plenty of these nested short loops because of algorithm such as Ranking, Leveland dependencies transitive closure computation. Here is the code used to benchmark all this: static void IterateForeachOnList(List list) { foreach(int i in list) { int j = i; } } static void IterateForOnListWithoutCountOptimization(List list) { for(int i=0; i < list.Count; i++) { int j = list [ i ] ; } } static void IterateForOnListWithCountOptimization(List list) { int count = list.Count; for (int i = 0; i < count; i++) { int j = list [ i ] ; } } static void IterateForeachOnArray(int[] array) { foreach (int i in array) { int j = i; } } static void IterateForOnArrayWithoutCountOptimization(int[] array) { for (int i = 0; i < array.Length; i++) { int j = array [ i ] ; } } static void IterateForOnArrayWithCountOptimization(int[] array) { int length = array.Length; for (int i = 0; i < length; i++) { int j = array [ i ] ; } } Here are the results obtained with the System.Diagnostics.Stopwatch class: The fact that for is more efficient than foreach results from the fact that foreach is using an enumerator object behind the scene. The fact that iterating on array is cheaper than iterating on List comes from the fact that the IL has instructions dedicated for array iteration. Here is the Reflector view of the methods: In the console output, we can see that foreach on array is a tiny bit more costly than for on array. Interestingly enough, I just checked that the C# compiler doesn’t use an enumerator object behind the scene for foreach on array. Some more interesting finding. The profiler dotTrace v3.1 gives some unrealistic results for this benchmark. IterateForeachOnList is deemed more than 40 times more costly than IterateForOnArray (instead of 5 times). I tested both RecordThreadTime and RecordWallTime mode of the profiler: Thus I also ran the benchmark with ANTS Profiler v4.1 and got some more realistic results, still not perfect however (IterateForeachOnList is now deemed 8 times more costly than IterateForOnArray,instead of 5 times). You can download the code of the benchmark here. All tests have been done with release compilation mode. More... |
![]() |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | Search this Thread |
| Display Modes | |
|
|
Algorithms and Data Structures
Programming Language Popularity
Code Collaboration
Podnet IRC Network
AmpHosted
Goal #1: 1,000 Blogs
Goal #2: 1,000 Wiki Pages
Goal #3: 300,000 Posts
Goal #4: 20,000 Threads
Done: 30%, 23%, 55%, 75%