473,659 Members | 2,681 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Performance hit in foreach?

This is a very simple question, but for moe reason I can't find an answer.
Do I take a performance hit if a foreach statement has to evaluate an
expression?

For example, consider the following:

foreach (DataColumn column in view.Row.Table. Columns)
{
// Do something
}

Do I gain anything by moving the evaluation outside the foreach, like this?

DataColumnColle ction myColumns = view.Row.Table. Columns;
foreach (DataColumn column in myColumns)
{
// Do something
}

Thanks.

--
David Veeneman
Foresight Systems
Aug 19 '06 #1
7 3803
David,

No, these are pretty much the same. The IEnumerable interface is going
to be obtained from the DataColumnColle ction exposed by the Columns property
on the DataTable class and then the methods/properties on that
implementation are going to be accessed.

Hope this helps.

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m
"David Veeneman" <da****@nospam. com (domain is my last name)wrote in
message news:%2******** ********@TK2MSF TNGP06.phx.gbl. ..
This is a very simple question, but for moe reason I can't find an answer.
Do I take a performance hit if a foreach statement has to evaluate an
expression?

For example, consider the following:

foreach (DataColumn column in view.Row.Table. Columns)
{
// Do something
}

Do I gain anything by moving the evaluation outside the foreach, like
this?

DataColumnColle ction myColumns = view.Row.Table. Columns;
foreach (DataColumn column in myColumns)
{
// Do something
}

Thanks.

--
David Veeneman
Foresight Systems

Aug 19 '06 #2
"David Veeneman" <da****@nospam. com (domain is my last name)wrote:
This is a very simple question, but for moe reason I can't find an answer.
Do I take a performance hit if a foreach statement has to evaluate an
expression?
Does your application run very slowly, and does profiling show that this
area is taking a lot of time?

That's the important question to ask, IMO.

-- Barry

--
http://barrkel.blogspot.com/
Aug 19 '06 #3
"Barry Kelly" <ba***********@ gmail.comwrote in message
news:eh******** *************** *********@4ax.c om...
"David Veeneman" <da****@nospam. com (domain is my last name)wrote:
>This is a very simple question, but for moe reason I can't find an
answer.
Do I take a performance hit if a foreach statement has to evaluate an
expression?

Does your application run very slowly, and does profiling show that
this
area is taking a lot of time?

That's the important question to ask, IMO.
Now, often times I do agree with your advice, but not here.
Such as when somebody advocates switching from a more maintainable piece
of code to something that is harder to understand....s imply in the name
of Optimization. Unless the difference is really significant...s tay with
understandable code.

In David's example the first sample is a smidge easier on the eye than
the second.
Both are easy to understand and maintain.
So which to choose???
Well, all things being equal...go with the one that doesn't take the
performance hit.

Now, in this case the Hit appears to not truly exist, so David once
again can take his pick.
Sure, many people a guilty of premature optimization, but sometimes it
is a question of Best Practices.

Bill

Aug 20 '06 #4
Bill Butler wrote:
Now, often times I do agree with your advice, but not here.
Such as when somebody advocates switching from a more maintainable piece
of code to something that is harder to understand....s imply in the name
of Optimization. Unless the difference is really significant...s tay with
understandable code.
I don't think what I said contradicted that :) But whenever someone here
agonizes over a small change like this that shouldn't affect algorithmic
complexity, whether or not it involves readability change one way or the
other, I recommend that they take it upon themselves to measure it. It's
the only way they'll really know, they'll find out how to measure
things, and hopefully they'll be aware enough of the big picture to know
when its not worth the agony. If they can't figure out these three
things, then I humbly think they might have other problems.
In David's example the first sample is a smidge easier on the eye than
the second.
Both are easy to understand and maintain.
So which to choose???
Well, all things being equal...go with the one that doesn't take the
performance hit.
If you think that the extra line doesn't amount to a de-optimization,
then this could be interpreted as an argument to use indexing on arrays
over and above foreach, for those scenarios which would work with
foreach, because there is a small performance hit for using foreach on
arrays.

Personally, I prefer fewer lines of simple code above almost everything
else, with classes written in such a way that the most performant
primitives (methods and properties etc.) are also the shortest and
simplest to use. For a concrete example, take a linked list class - such
a class shouldn't have an integer indexer, because it would make a
simple for-loop iteration a quadratic operation.
Now, in this case the Hit appears to not truly exist, so David once
again can take his pick.
Sure, many people a guilty of premature optimization, but sometimes it
is a question of Best Practices.
Again, I could interpret this as a mandate for inclusion of a certain
class of patterns into a Bible of Code Patterns, to be enforced in a
team. I think that such a Bible can be useful when the patterns matter
for correctness (e.g. think of the Dispose pattern), or for alternatives
that differ in algorithmic complexity (e.g. turning a linear algorithm
into a quadratic algorithm, with the linked list class above), but not
for things like this.

To put it another way: I think bibles of approved code patterns can work
if such a bible includes a rationale for each item (including the
qualifications above too). I'd prefer if people coding thought about
their code as they wrote it and knew what they were doing, rather than
following Best Practices on such a small scale that it can lead to
cargo-cult programming, and an attempt to turn people into cogs.

-- Barry

--
http://barrkel.blogspot.com/
Aug 20 '06 #5

David Veeneman (domain is my last name) wrote:
This is a very simple question, but for moe reason I can't find an answer.
Do I take a performance hit if a foreach statement has to evaluate an
expression?

For example, consider the following:

foreach (DataColumn column in view.Row.Table. Columns)
{
// Do something
}
No. The code you gave translates into this:

IEnumerator e = view.Row.Table. Columns.GetEnum erator();
while (e.MoveNext())
{
DataColumn column = (DataColumn)e.C urrent;
// Do something
}

As you can see, view.Row.Table. Columns is evaluated only once.

Aug 20 '06 #6
"Barry Kelly" <ba***********@ gmail.comwrote in message
news:eh******** *************** *********@4ax.c om...
"David Veeneman" <da****@nospam. com (domain is my last name)wrote:
>This is a very simple question, but for moe reason I can't find an
answer.
Do I take a performance hit if a foreach statement has to evaluate an
expression?

Does your application run very slowly, and does profiling show that this
area is taking a lot of time?

That's the important question to ask, IMO.
Agreed. I would also ask if one has read The C# Programming Language (or has
access to a copy).
Aug 21 '06 #7
"Barry Kelly" <ba***********@ gmail.comwrote in message
news:38******** *************** *********@4ax.c om...
Bill Butler wrote:
Barry,

I suspect that I misread the intention of your post, becaue I find
myself agreeing with you on most evey point.
Example:
I prefer foreach over a for loop due to the increased clarity of
purpose. If I was coding a tight loop and foreach was proven to be the
bottleneck...th en I would consider switching.

When I originaly read your post I took it to mean.
"If it isn't causing a problem, why are you worried."

And my thought was
"Knowledge is power, it may not matter in THIS case but it may down
the road".

I, unfortunately, have dealt with way to many developers who NEVER
consider algorithmic complexity when designing their code. It always
comes as a shock to them that it acts like a pig, because they didn't
think about such things at design time. Then, the whole thing needs to
be reworked to fix things that should have been right from the
beginning.

I can see now that you were NOT advocating :
"code it however you like as long as the performance hit is not
obvious"

Anyway,
I really should read things twice before responding.

Bill

>
>Now, often times I do agree with your advice, but not here.
Such as when somebody advocates switching from a more maintainable
piece
of code to something that is harder to understand....s imply in the
name
of Optimization. Unless the difference is really significant...s tay
with
understandab le code.

I don't think what I said contradicted that :) But whenever someone
here
agonizes over a small change like this that shouldn't affect
algorithmic
complexity, whether or not it involves readability change one way or
the
other, I recommend that they take it upon themselves to measure it.
It's
the only way they'll really know, they'll find out how to measure
things, and hopefully they'll be aware enough of the big picture to
know
when its not worth the agony. If they can't figure out these three
things, then I humbly think they might have other problems.
>In David's example the first sample is a smidge easier on the eye
than
the second.
Both are easy to understand and maintain.
So which to choose???
Well, all things being equal...go with the one that doesn't take the
performance hit.

If you think that the extra line doesn't amount to a de-optimization,
then this could be interpreted as an argument to use indexing on
arrays
over and above foreach, for those scenarios which would work with
foreach, because there is a small performance hit for using foreach on
arrays.

Personally, I prefer fewer lines of simple code above almost
everything
else, with classes written in such a way that the most performant
primitives (methods and properties etc.) are also the shortest and
simplest to use. For a concrete example, take a linked list class -
such
a class shouldn't have an integer indexer, because it would make a
simple for-loop iteration a quadratic operation.
>Now, in this case the Hit appears to not truly exist, so David once
again can take his pick.
Sure, many people a guilty of premature optimization, but sometimes
it
is a question of Best Practices.

Again, I could interpret this as a mandate for inclusion of a certain
class of patterns into a Bible of Code Patterns, to be enforced in a
team. I think that such a Bible can be useful when the patterns matter
for correctness (e.g. think of the Dispose pattern), or for
alternatives
that differ in algorithmic complexity (e.g. turning a linear algorithm
into a quadratic algorithm, with the linked list class above), but not
for things like this.

To put it another way: I think bibles of approved code patterns can
work
if such a bible includes a rationale for each item (including the
qualifications above too). I'd prefer if people coding thought about
their code as they wrote it and knew what they were doing, rather than
following Best Practices on such a small scale that it can lead to
cargo-cult programming, and an attempt to turn people into cogs.

-- Barry

--
http://barrkel.blogspot.com/

Aug 21 '06 #8

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

Similar topics

3
2583
by: Randell D. | last post by:
Folks, A ng poster recently questioned their usage/creation of arrays and their correct syntax. I got the idea to performance test from a recent (excellent) PHP Tutorial article that was in Linux Format magazine (which dealt with performance). The original poster had a reply from someone who had said using $testArray was better (and proper) than $testArray I *had* believed this to be correct... but... against my better judgement, I
0
4297
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...
2
1875
by: Joris Dobbelsteen | last post by:
Dear, I've made a little tool that synchronizes my ISA Server block list with a database. However the performance of this is very low. I'm retreiving 41140 rows from the database, storing them in a hash table and clearing the input tables within 1 or 2 seconds. Getting 41140 rows from the ISA server destination set takes me an awsome 173 seconds!
3
1368
by: MattC | last post by:
Hi, I have a collection class derived from ArrayList, it stores colletions of objects from my objet model. I Didn't want to have to create a specialised collection for each object type so I created the following static method. public static MyCollection CreateGenericCollection(DataTable rates, Assembly a, Type t) { MyCollection c = new MyCollection(); // create new collection
3
1639
by: AK | last post by:
Hi Everyone, For Last a few weeks I have been involved with performance tuning of an application. I have observed that if I do a loop over a collection (ArrayList/HashTable) which has 50000 objects in one shot then it takes about 15 minutes to do the computation. But if I break this to loop of only 5000 objects and do all computation in 10 loops of 5000 each then it takes about 1 minutes 30 seconds. I am trying to find a reason for...
15
1353
by: MuZZy | last post by:
Hi, Consider this: ArrayList al = new ArrayList(); FillList(al); /// NOW TWO SCENARIOS: /// 1. for (int i = 0 ; i < al.Count ; i++)
4
1391
by: Linan | last post by:
Recently I wrote a program to help my wife to extract data from about 500 excel files. For each file, around 1000 cells are visited and the texts are retrieved. Firstly I wrote a python script, used win32com module. The program ran well, but took 78 mins to accomplished the task. Of course it was a little bit slow, so I gave csharp a go. The csharp program took 72 mins. Both Excel and .Net are MS product, run on a microsoft operating
5
1901
by: Markus Ernst | last post by:
Hello A class that composes the output of shop-related data gets some info from the main shop class. Now I wonder whether it is faster to store the info in the output class or get it from the main class whenever it is needed: class shop_main { var $prices = null; function &get_prices() {
7
4520
by: jehugaleahsa | last post by:
I wrote a simple method that allows me to pass a delegate to find a value in a list. I already had a set of methods for doing comparisons: less, greater, equal, equivalent, etc. However, find algorithms always compare the element in the list to a given value. In other words, I needed to bind one value for all the comparisons. I wrote a simple Bind1st method that looks like this: public delegate R Operation<R, T>(T value);
0
8428
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
8339
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
8851
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
8751
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
8629
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6181
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4176
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...
2
1982
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1739
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.