473,811 Members | 3,467 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 13100
Hi,

"Jim H" <ji**@nospam.no spamwrote in message
news:uV******** ******@TK2MSFTN GP02.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.no spamwrote:
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.co m>
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******** ********@TK2MSF TNGP04.phx.gbl. ..
Hi,

"Jim H" <ji**@nospam.no spamwrote in message
news:uV******** ******@TK2MSFTN GP02.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.no spamwrote:
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._internal MyThings.ToArra y(typeof(MyThin g)); }
}

(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:
"Performanc e 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
4307
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 code everytime I found more than one method to perform a single task. I timed each method to find which would complete faster. I thought I'd share my most recent results which (I believe) should help those write their programs to be more...
104
7208
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 foeach(Color c in Red..Blue) { } // using enums It should work with all integral datatypes. Maybe we can step a bit further: foeach(int i in 1..10, 30..100) { } // from 1 to 10 and 30 to hundred
15
2679
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 "foreach" loop instead of a "for" loop. This made absolutely no sense to me, but the author had posted his code and timing results. The "foreach" (a VB and other languages construct) was 0.01 seconds to access 1000 lines in rich text box,...
13
14501
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 findListBox.listBox2.Items) { listBox2.Items count changed, restart this foreach } Thanks for any help.
4
2568
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 extension of the first: foreach (array_expression as $value) statement
4
2208
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' ='90'), ); $keys = array();
19
2936
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
33374
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 code is here: foreach ( string propertyName in ht.Keys ) { this.setProperty( propertyName, ht );
2
3234
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 on the homepage of a site, i wanted to truncate the content to like the first 75 characters and then put "..." (a perfect use of the smarty "truncate" modifier) and then give the visitor a link to read the whole article. But since "the_content" is a...
0
9727
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9605
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10647
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10386
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9204
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6889
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5554
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4339
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3865
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.