Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / Languages / C# / February 2008

Tip: Looking for answers? Try searching our database.

Which is faster for arrays - foreach or for ( i... ) ?

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
DoB - 06 Feb 2008 09:50 GMT
Hi,

Given the following declaration:

       object[] a = new object[SOME_BIG_NUMBER];

which code is faster?

1.
       foreach ( object o in a )
           DoSomethingWith(o);

2.
       int iSize = a.Length;
       int i;
       foreach ( i = 0; i < iSize; i++ )
           DoSomethingWith(a[i]);

And why?

Regards,
DoB
DoB - 06 Feb 2008 09:57 GMT
>        foreach ( i = 0; i < iSize; i++ )

Sorry, there was a typo here, of course ;-). should be "for".

DoB
Alberto Poblacion - 06 Feb 2008 10:40 GMT
> Given the following declaration:
>
[quoted text clipped - 13 lines]
>
> And why?

  In general, "for i" used with an array is faster than "foreach", the
reason being that "for i" only needs to increment and compare an integer and
do an indexing operation for every iteration, which are fast operations,
while "foreach" needs to call into IEnumerator to move to the next element
and then retrieve the current one. These are two method calls, in addition
to whatever is inside the methods, so it has a bigger overhead.
Ben Voigt [C++ MVP] - 06 Feb 2008 16:03 GMT
>> Given the following declaration:
>>
[quoted text clipped - 21 lines]
> two method calls, in addition to whatever is inside the methods, so
> it has a bigger overhead.

arrays are a special case for the foreach keyword, the compiler
automatically avoids using IEnumerator
Jon Skeet [C# MVP] - 06 Feb 2008 11:06 GMT
> Given the following declaration:
>
>         object[] a = new object[SOME_BIG_NUMBER];
>
> which code is faster?

I wouldn't concentrate on which code is faster until I've proved it
matters - at which point I'd have numbers to compare if I made
changes.

I'd concentrate on which is more readable, and simpler - in which case
"foreach" wins in most situations.

Don't micro-optimise until you know you've got a problem - and if you
know you've got a problem, that should include hard figures, which
will make it easy to test changes.

Jon
DoB - 06 Feb 2008 11:26 GMT
> Don't micro-optimise until you know you've got a problem - and if you
> know you've got a problem, that should include hard figures, which
> will make it easy to test changes.

I actually came across a situation in which I wanted to change "foreach" to
"for" for some reasons (not performance-related) and before making a change
I wanted to know what was an impact on performance.

DoB
Jon Skeet [C# MVP] - 06 Feb 2008 11:37 GMT
> > Don't micro-optimise until you know you've got a problem - and if you
> > know you've got a problem, that should include hard figures, which
[quoted text clipped - 3 lines]
> "for" for some reasons (not performance-related) and before making a change
> I wanted to know what was an impact on performance.

Miniscule either way, unless you're really, really not doing anything
in the loop. If you have performance concerns, measuring them is
crucial.

I wouldn't try to micro-optimise the for loop, btw. Just do:

for (int i=0; i < myArray.Length; i++)
{
}

instead of using the temporary variable. I seem to recall that this is
actually faster in some situations, but it's certainly more readable.

Jon
DoB - 06 Feb 2008 12:49 GMT
> I wouldn't try to micro-optimise the for loop, btw. Just do:
>
[quoted text clipped - 4 lines]
> instead of using the temporary variable. I seem to recall that this is
> actually faster in some situations, but it's certainly more readable.

I've made some tests and... yes... you are absolutely right - this is a bit
faster.
Why? Optimisation?

DoB.
Jon Skeet [C# MVP] - 06 Feb 2008 12:53 GMT
> > I wouldn't try to micro-optimise the for loop, btw. Just do:
> >
[quoted text clipped - 8 lines]
> faster.
> Why? Optimisation?

The JIT compiler recognises the pattern, and can remove the array
bounds check within the loop, as I understand it.

Signature

Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet   Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk

DoB - 07 Feb 2008 09:39 GMT
>> I've made some tests and... yes... you are absolutely right - this is a
>> bit
[quoted text clipped - 3 lines]
> The JIT compiler recognises the pattern, and can remove the array
> bounds check within the loop, as I understand it.

What is interesting, I tested in debug mode. Looks like it is optimised,
too.

DoB
Laura T. - 06 Feb 2008 15:33 GMT
Just my 2 cents.. I find the Array.ForEach<> most readable, but maybe not
the most efficient:

object[] arr = new object[SOME_BIG_NUMBER];
Array.ForEach<object>(arr, new Action<object>(DoSomething));

>> Given the following declaration:
>>
[quoted text clipped - 14 lines]
>
> Jon
Dejan Stanic - 06 Feb 2008 18:51 GMT
> Just my 2 cents.. I find the Array.ForEach<> most readable, but maybe not
> the most efficient:

Definitely not efficient.

LP,
Dejan
Jon Skeet [C# MVP] - 06 Feb 2008 18:56 GMT
> > Just my 2 cents.. I find the Array.ForEach<> most readable, but maybe not
> > the most efficient:
>
> Definitely not efficient.

Well, to the extent that there's a delegate call each time. As ever,
it's unlikely to be significant in most code.

Signature

Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet   Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.