Friday, July 6, 2007

FOR v/s FOREACH: Different Perspectives.

Over the years I have been coding just to get the work done. Now since last few months, I realized the importance of every single step taken to improve the performance and writing the code that is optimized.

But during this process of optimization, at times I felt if Approach 1 was more optimized or Approach 2.

One such condition was when I used For loops to iterate through the items of collection.

Now heres the theory:

FOR LOOP:

int[] indexArray = new int[5];
int total = 0;
for(int i = 0; i < indexArray.Length; i++)
{
total += indexArray[i];
}


FOREACH LOOP:

int[] indexArray = new int[5];
int total = 0;
foreach(int i in indexArray)
{
total += i;
}

The advantage of a foreach loop over a for loop is that it is not al all necessary to know the number of items within the collection when an iteration starts. This avoids iterating off the end of the collection using an index that is not available. A foreach loop also allows code to iterate over a collection without first loading the collection in entirety into memory.

So herein we can safely assume that using foreach is an optimized approach rather than using a for loop.

NOW LETS MOVE TO THE OTHER SIDE OF IT:

If we closely look at the IL Code for the above two constructs:

FOR LOOP:

Instruction
cmp dword ptr [eax+4],0
jle 0000000F
mov ecx,dword ptr [eax+edx*4+8]
inc edx
++icmp esi,dword ptr [eax+4]
jl FFFFFFF8


Here, the comparision is done at two stages:
1. For the first run it is done only once to check if the counter is good to continue into the loop.
2. Inside the loop where it is exactly comparing and recalling the code.
This is very well optimized in the loop.

FOREACH LOOP:

Instruction

cmp esi,dword ptr [ebx+4]
jl FFFFFFE3
cmp esi,dword ptr [ebx+4]
jb 00000009
mov eax,dword ptr [ebx+esi*4+8]
mov dword ptr [ebp-0Ch],eax
mov eax,dword ptr [ebp-0Ch]
add dword ptr [ebp-8],eax
inc esi
cmp esi,dword ptr [ebx+4]
jl FFFFFFE3


Clearly the two syntaxes are different. There are some unwanted comparisions and some moves that are exactly not required. Thats because foreach treats everything as a collection and hence uses the code for the same which reduces the performance if it is not a collection and is a simple array only.

So still I am at indecision whether For is an optimized version or ForEach is??.............. :(

--Ashutosh

No comments:

Post a Comment