473,320 Members | 1,691 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,320 software developers and data experts.

Efficiency of foreach vs for loop

When dealing with reference types, is there an efficiency advantage in using
a for loop instead of a foreach? I though I read somewhere that when using
value types a for loop was more efficient because of the boxing involved
when using foreach.

Thanks,
Jim
Jan 30 '07 #1
5 13075
Hi,

"Jim H" <ji**@nospam.nospamwrote in message
news:uV**************@TK2MSFTNGP02.phx.gbl...
| When dealing with reference types, is there an efficiency advantage in
using
| a for loop instead of a foreach? I though I read somewhere that when
using
| value types a for loop was more efficient because of the boxing involved
| when using foreach.

This has been discussed here ad-nauseam, look in the archives for those
thread.

The conclusion is that you should your time focused in more important
matters :)

I do not see how the boxing can be avoided with either solution though.
--
Ignacio Machin
machin AT laceupsolutions com
Jan 30 '07 #2
Jim H <ji**@nospam.nospamwrote:
When dealing with reference types, is there an efficiency advantage in using
a for loop instead of a foreach? I though I read somewhere that when using
value types a for loop was more efficient because of the boxing involved
when using foreach.
It depends on *exactly* which collection you're looking through.
However, usually the difference is so small, you should use whichever
you find more readable. (IMO that's usually foreach.)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jan 30 '07 #3
Thanks to both of you (John and Ignacio).

I'll just use whatever looks easier to read for others in each situation.

jim
"Ignacio Machin ( .NET/ C# MVP )" <machin TA laceupsolutions.comwrote in
message news:%2****************@TK2MSFTNGP04.phx.gbl...
Hi,

"Jim H" <ji**@nospam.nospamwrote in message
news:uV**************@TK2MSFTNGP02.phx.gbl...
| When dealing with reference types, is there an efficiency advantage in
using
| a for loop instead of a foreach? I though I read somewhere that when
using
| value types a for loop was more efficient because of the boxing involved
| when using foreach.

This has been discussed here ad-nauseam, look in the archives for those
thread.

The conclusion is that you should your time focused in more important
matters :)

I do not see how the boxing can be avoided with either solution though.
--
Ignacio Machin
machin AT laceupsolutions com


Jan 30 '07 #4
On Jan 30, 12:33 pm, "Jim H" <j...@nospam.nospamwrote:
When dealing with reference types, is there an efficiency advantage in using
a for loop instead of a foreach? I though I read somewhere that when using
value types a for loop was more efficient because of the boxing involved
when using foreach.
There are situations in which "for" is definitely worse, as well. For
example, if you have a property that builds and returns an aggregate
structure such as an array:

public MyThing[] MyThings
{
get { return
(MyThing[])this._internalMyThings.ToArray(typeof(MyThing)); }
}

(Yes, I know that this is bad practice, and that FxCop specifically
warns against it, but say you had a property like this....)

Then this

for (int x = 0; x < myObj.MyThings.Length; x++)
{
MyThing thing = myObj.MyThings[i];
}

gives absolutlely horrible performance, while this:

foreach (MyThing thing in myObj.MyThings)
{
}

gives good performance.

Again, it all depends on what you're doing, and in the end it's
usually bad designs that kill performance, not using one style of loop
versus another.

Jan 30 '07 #5
Hi Jim,

Yes, I also agree with others that we should pay more attention to other
more performance concern places. However, if your application manipulates
string very often, the "for" may improve some performance, please search
"Use For Loops for String Iteration" section in the link below:
"Performance Tips and Tricks in .NET Applications"
http://msdn2.microsoft.com/en-us/library/ms973839.aspx

Thanks.

Best regards,
Jeffrey Tan
Microsoft Online Community Support
==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.

Jan 31 '07 #6

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

Similar topics

0
by: Randell D. | last post by:
Folks, Ever since reading an interesting article in Linux Format on PHP whereby suggested code writing was made that could enhance performance on a server, I've started testing various bits of...
104
by: cody | last post by:
What about an enhancement of foreach loops which allows a syntax like that: foeach(int i in 1..10) { } // forward foeach(int i in 99..2) { } // backwards foeach(char c in 'a'..'z') { } // chars...
15
by: Mike Lansdaal | last post by:
I came across a reference on a web site (http://www.personalmicrocosms.com/html/dotnettips.html#richtextbox_lines ) that said to speed up access to a rich text box's lines that you needed to use a...
13
by: TrintCSD | last post by:
How can I reset the collections within a foreach to be read as a change from within the foreach loop then restart the foreach after collections has been changed? foreach(string invoice in...
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: Markus Ernst | last post by:
Hi While looping through an array I extract all keys on the fly, as in this example: $data = array( array('name' ='Helen', 'age' ='40'), array('name' ='Mark', 'email' ='mark@xyz.com', 'age'...
19
by: vamshi | last post by:
Hi all, This is a question about the efficiency of the code. a :- int i; for( i = 0; i < 20; i++ ) printf("%d",i); b:- int i = 10;
3
by: Akira | last post by:
I noticed that using foreach is much slower than using for-loop, so I want to change our current code from foreach to for-loop. But I can't figure out how. Could someone help me please? Current...
2
by: recordlovelife | last post by:
So I am trying to display a title, date, and content of a wordpress blog. Word press provides nice drop in functions to get the job done with simple names like "the_title", and the "the_content" But...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

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.