• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 504
  • Last Modified:

Is foreach slow?

If i have a collection, and use foreach loop to go thru it, is that slow? someone on the team said foreach is slow and there's a better way of doing it (not sure what way that is tho)
4 Solutions

Although I am not an expert in ASP, I will give it a shot.  It really depends on what is going on in the foreach loop.  Does it involve one or more IF statements within the loop?  Multiple IF statements can slow it down as each one has to be processed regardless.

If you are using IF statements within the loop to check for different values of the same variable, then you can use a switch statement to speed that up.  Kind of similar to this:


Other than that, I am honestly not sure what could be faster than that since my experience with ASP.net is weak.
foreach is the recommended way to do it. It is after all a loop - what other way can you do a loop.  You could maybe use a repeater which looks cleaner but is actually worse.
But ultimately it depends on what the data is, how you are using it etc. e.g. you don't loop a thousand times to find one value.
Obadiah ChristopherCommented:
foreach(GridViewRow gvRow in gv1.Rows)


GridViewRow gvRow;
for(int i = 0; i < gv1.Rows.Count; i++)
      gvRow = gv1.Rows[i];

Open in new window

Alan WarrenApplications DeveloperCommented:
Yes, I reckon it is/possibly could be slower, of course it depends on the type of 'each'. If each 'each' is an integer, wouldn't make much difference.

If you were doing:
  for each ctl as control in me.controls
  ' the ctl is instantiated, takes resources, especially if it's a complex control.
  ' you can verify that by using 'With' to expose the properties of the ctl inside the for each loop.
  With ctl
    .text = "hello world"
  End With

On the other hand, if you were looping like:
  for i = 0 to me.controls.count
  ' then the control is not instantiated until you say so, all you have instantiated is an integer array().

Alan ";0)
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now