473,386 Members | 1,705 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

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

DoB
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
Feb 6 '08 #1
10 1716
DoB
foreach ( i = 0; i < iSize; i++ )

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

DoB
Feb 6 '08 #2
"DoB" <Do*@dob.comwrote in message
news:ex**************@TK2MSFTNGP06.phx.gbl...
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?
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.

Feb 6 '08 #3
On Feb 6, 9:50 am, "DoB" <D...@dob.comwrote:
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
Feb 6 '08 #4
DoB
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
Feb 6 '08 #5
On Feb 6, 11:26 am, "DoB" <D...@dob.comwrote:
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.
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
Feb 6 '08 #6
DoB
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.

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

DoB.
Feb 6 '08 #7
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));

"Jon Skeet [C# MVP]" <sk***@pobox.comha scritto nel messaggio
news:2f**********************************@s37g2000 prg.googlegroups.com...
On Feb 6, 9:50 am, "DoB" <D...@dob.comwrote:
>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
Feb 6 '08 #8
Alberto Poblacion wrote:
"DoB" <Do*@dob.comwrote in message
news:ex**************@TK2MSFTNGP06.phx.gbl...
>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?

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.
arrays are a special case for the foreach keyword, the compiler
automatically avoids using IEnumerator
Feb 6 '08 #9
"Laura T." <LT*****@yahoo.comje napisal v sporocilo
news:%2****************@TK2MSFTNGP04.phx.gbl ...
Just my 2 cents.. I find the Array.ForEach<most readable, but maybe not
the most efficient:
Definitely not efficient.

LP,
Dejan

Feb 6 '08 #10
DoB
>I've made some tests and... yes... you are absolutely right - this is a
>bit
faster.
Why? Optimisation?

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
Feb 7 '08 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Phil Powell | last post by:
/*-------------------------------------------------------------------------------------------------------------------------------- Parameters: $formField1: The name of the first array $formField2:...
6
by: Bart Nessux | last post by:
How is this done in php? I've tried several variations of the following: contact_array = ($_POST, $_POST, $_POST, $_POST, $_POST); The ultimate goal is to insert the array into a table in...
6
by: ubccis | last post by:
Hi. Does for each for on multidimensional arrays? For example, if one element of $in is $course_list and I want to echo all everything in course_list
4
by: Sjoerd | last post by:
Summary: Use foreach(..) instead of while(list(..)=each(..)). --==-- Foreach is a language construct, meant for looping through arrays. There are two syntaxes; the second is a minor but useful...
4
by: Jack E Leonard | last post by:
I'm looping through the keys and values of a form submission using foreach($_POST as $key => $value) echo "$key = $value<br>"; No problems there. All works as expected. But seveal of the...
2
by: assgar | last post by:
Hi Developemnt on win2003 server. Final server will be linux Apache,Mysql and PHP is being used. I use 2 scripts(form and process). The form displays multiple dynamic rows with chechboxs,...
0
by: mantrid | last post by:
I was thinking along these lines initially but didnt know much about arrays. So thought the easiest way was to use two separate fields. However the two fields match, in that the commar separated...
28
by: natarajmtech | last post by:
Hi all, I have defined some array variables a ***************************************** @L=('CTT','CTC','CTA','CTG','TTA','TTG'); @S=('TCT','TCC','TCA','TCG','AGT','AGC'); ...
110
by: fjm | last post by:
For some reason, I have always had a hard time understanding arrays as they pertain to php and databases. I understand associative arrays just fine but when there are multidimensional arrays, I kinda...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.