Re: Optimal use of foreach

Greg Young <[email protected]>
Newsgroups gmane.comp.windows.devel.dotnet.advanced
Message-ID <[email protected]>
>for loops are usually used in inner loops where you don't want to create
>millions of new IEnumerator<T>. They are also slightly faster on arrays, but
>the vast majority of the time, foreach is fine and makes the code clearer.

They are not slightly faster on arrays.

Please see: http://codebetter.com/blogs/gregyoung/archive/2006/06/12/146372.aspx
which addresses this point in particular (I believe the originating
point of this misconception was a few people at MS) and
http://codebetter.com/blogs/gregyoung/archive/2006/06/11/146343.aspx
for a more in depth look at how for loops work (its old and there are
some minor revisions to the JIT but most still holds true).

Cheers,

Greg

On Tue, Jan 27, 2009 at 11:51 PM, Sébastien Lorion
<[email protected]> wrote:
> When you use foreach, it actually calls myDictionary.Keys.GetEnumerator()
> which returns a new instance of IEnumerator<T>. That enumerator is then used
> during the loop and Keys is never called again. Open up Reflector and take a
> look at the code, you will better understand what's going on this way ;)
>
> for loops are usually used in inner loops where you don't want to create
> millions of new IEnumerator<T>. They are also slightly faster on arrays, but
> the vast majority of the time, foreach is fine and makes the code clearer.
>
> Sébastien
> On Tue, Jan 27, 2009 at 8:43 PM, Mont Rothstein <[email protected]>wrote:
>
>> When using foreach if the collection is a property will it be called on
>> each
>> pass or only once?
>>
>> Can I do:
>>
>> foreach (string key in myDictionary.Keys)
>> {
>> }
>>
>> or will that call Keys each time, therefore requiring that I do:
>>
>> Dictionary<string, string>.KeysCollections keys;
>>
>> keys = myDictionary.Keys;
>>
>> foreach (string key in keys)
>> {
>> }
>>
>> Thanks,
>> -Mont
>>
>> ===================================
>> View archives and manage your subscription(s) at
>> http://peach.ease.lsoft.com/archives
>>
>
> ===================================
> View archives and manage your subscription(s) at http://peach.ease.lsoft.com/archives
>



-- 
It is the mark of an educated mind to be able to entertain a thought
without accepting it.

===================================
View archives and manage your subscription(s) at http://peach.ease.lsoft.com/archives
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.