Re: Which scope for variables being used in a loop?



"Manish Pandit" wrote ...
In this case, the variables are allocated on the stack, as they are
"local". I do not think this could lead to out of memory (unless the
collection is gigantic). Personally I never like the idea of declaring
variables within a loop, and have not seen a lot of instances where it
is done.

There are plenty of instances where variables are declared inside a loop, and there are good, solid engineering reasons to do so.

Declaring the variable inside a loop, or any other block, limits its scope to that block. If it is not needed outside the block, then its scope matches its use.

The variable remains in the JVM until the end of the stack frame, even after it goes out of scope; if it isn't nulled then it won't be gced until the method ends. It is still inaccessible to code outside its block.

Limiting variable scope is a good principle of defensive programming. If a variable doesn't linger after its use, nor is declared until needed, it has less chance to make mischief. (Joshua Bloch touches on this in /Effective Java/.)

Use of the for ( T thing : things ) idiom is an example of scope limitation. The variable "thing" is only in scope for the loop.

- Lew
.



Relevant Pages

  • Re: About String
    ... My idea is that every statement list is a scope. ... You declare something inside a loop body, ... The same sense as declare blocks. ... SCOPE [DECLS] STATEMENTS END-SCOPE ...
    (comp.lang.ada)
  • Re: Which scope for variables being used in a loop?
    ... can't be GC'd until the scope they are declared in exist. ... inside of the loop. ... overlay local allocations in another loop. ... declaration itself, such that the pointer-value of the variable is ...
    (comp.lang.java.programmer)
  • Re: Scope Best Practice
    ... creating a new object versus the cost of maintaining it in memory?" ... the object is ready for GC once the loop is complete ( ... even if it remains in scope because it is not being referenced anywhere ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Query regd. memory usage
    ... The decision of where to declare a variable, or where to reuse it, should not ... Declaring the "bean" variable inside the loop limits its scope to the loop. ...
    (comp.lang.java.programmer)
  • Re: Dereferencing Hash of Arrays
    ... I guess it has the opposite effect. ... is to always declare variables in the shortest scope possible. ... Change that while loop to: ... iteration begins, %data will be destroyed and your next iteration will ...
    (comp.lang.perl.misc)