2

how can i implement this foreach loop with for loop? because i heard that for loop is much faster than foreach loop.

   foreach (RV item in gridview.SelectedItems.ToList())
   {
        R req= db.Requests.Single(x => x.Id == item.Id);
        ...
   }
1
  • That's a trivial for loop; I don't see your question. Commented Dec 25, 2011 at 18:28

3 Answers 3

11

You heard incorrectly.
for loops are not much faster than foreach loops.
In fact, for some collections, foreach loops are much faster than for loops.

ToList() is slower than either of them.

If you really want to make your code faster, you should use an O(n) LINQ join instead of the O(n2) Single() call.

Sign up to request clarification or add additional context in comments.

4 Comments

When does foreach loop faster then for loop?
@gdoron: When using a linked list as an IList<T>.
Can you please explain why, or provide a link?
@gdoron: The indexer of a linked list of O(n) since it needs to start from the beginning every time.
0
for (int i = 0; i < gridview.SelectedItems.Count(); i++)
{
    R req = db.Requests.Single(x => x.ID == (gridview.SelectedItems(i) as RV).Id);
    ...
}

Although I doubt there will be any noticeable performance gain.

1 Comment

There will be an (immeasurable) performance loss from the Count()s.
0

There is no point in converting your selected items to a list, if you are enumerating them with foreach anyway. Also a for loop requires you to call ToList, which internally uses a foreach!

I do not know, if your o/r-mapper can cope with Contains. If it does try this:

var items = db.Requests.Where(x => gridview.SelectedItems.Contains(x.Id));

This will reduce the number of database requests. This is where time gets lost, not in the foreach!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.