Efficiency of entering a request into a C # foreach condition

I came across this C # code in a project today, and I could not help but doubt its effectiveness:

SPList spList = spWeb.GetListCustom("tasks"); foreach (SPListITem item in spList.GetItems(query)) { //... do something with the SPListCollection it returned } 

Being against the backdrop of Java, spList.GetItems (query) definitely made me think that its performance was a success. I would do something like the following to improve it:

 SPList spList = spWeb.GetListCustom("tasks"); SPListIteCollection taskListCollection = taskList.GetItems(query); foreach (SPListITem item in taskListCollection) { //... do something with the SPListCollection it returned } 

However, the code is in C # ...

So my question is: could the code I suggested above improve performance, or did I miss something fundamental in the for # C # loop?

Thanks.

+4
source share
3 answers

Two blocks of code are completely identical and will be compiled for the same IL in Release mode.

Unlike the regular for loop, the foreach will only use the collection once (to call GetEnumerator ). Therefore, you have nothing to worry about.

+14
source

The second code block is easy to read, not other benefits. I could better understand what foreach is playing with SPListIteCollection .

0
source

enumerator in foreach is evaluated only once, also works in java.

0
source

Source: https://habr.com/ru/post/1302187/


All Articles