Re: Best practice using large objects in foreach
- From: Barry Kelly <barry.j.kelly@xxxxxxxxx>
- Date: Thu, 27 Jul 2006 16:30:18 +0100
"Benny" <bennyandlinds@xxxxxxxxx> wrote:
I just wanted to throw the discussion out there on what the best
practice people feel is for using large objects in a foreach loop. For
example if you are reusing an Image object in a loop like this (letters
above snippets are for reference purposes):
There are two issues involved here:
1) The scope of locals
2) Disposal of objects which implement IDisposable
The basic rules of thumb, correspondingly, are:
1) The scope should be as small as possible, but large enough so the
variable is visible everywhere it's needed in the function. Preferably,
locals shouldn't be declared until there's a value to initialize them
with - this isn't always possible, though.
2) Locals which implement IDisposable should be used inside a 'using' if
possible; fields which implement IDisposable should be disposed of in
the Dispose(bool) method, and the class should implement the Dispose
pattern.
C
foreach ( string s in myList )
{
using ( Image img = Image.FromFile( s );
{
// operate on img
}
}
So, the above is the best option, IMHO.
About local scoping: the scope information of the variable is lost after
compiling. The JIT compiler in the CLR works out the actual lifetime of
the local by analysing when and where it is used. If you try compiling
two programs, one which uses your option B and one which uses C, you'll
find that they compile to the same IL.
-- Barry
--
http://barrkel.blogspot.com/
.
- Follow-Ups:
- Re: Best practice using large objects in foreach
- From: Barry Kelly
- Re: Best practice using large objects in foreach
- From: Marc Gravell
- Re: Best practice using large objects in foreach
- References:
- Best practice using large objects in foreach
- From: Benny
- Best practice using large objects in foreach
- Prev by Date: Re: Timer not working on my Service.
- Next by Date: Re: How do you get around this?
- Previous by thread: Re: Best practice using large objects in foreach
- Next by thread: Re: Best practice using large objects in foreach
- Index(es):
Relevant Pages
|