Re: Best practice using large objects in foreach

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance



"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/
.



Relevant Pages

  • Re: Long.valueOf(long) CodeAttribute max_locals wrong?
    ... final int offset = 128; ... view" of local variables, or with the JVM view of local variables? ... Compiling code with debug information should provide proper initialization code for the final int offset, because debuggers may access the names and/or values of the local variables. ... public class Locals { ...
    (comp.lang.java.machine)
  • Re: ANS Forth portability issue
    ... When locals are used in a colon definition some systems put ... one or more locals wordlists at the head of the search order, ... When compiling, the compiler looks ...
    (comp.lang.forth)
  • Re: how to find out the address of a variable after I compile the C file
    ... "pete" wrote in message ... after compiling, I want to know the addresses of the two variables in ... In the case of recursive functions, different instances of the same locals may exist in several places. ...
    (comp.lang.c)
  • Re: Error C3018 - Too many symbols
    ... use locals and static arrays ... > I received this error when compiling my clipper program. ...
    (comp.lang.clipper)