tags:

views:

191

answers:

8

One common dilemma I have faced throughout programming is regarding declaring variables inside a loop. Say I have to perform something like the following:

List list=myObject.getList();
Iterator itr=list.iterator();
while (itr.hasNext()){
    BusinessObject myBo=(BusinessObject)itr.next();
    process(myBo);
}

In the above snippet, should myBo be declared outside the loop or does declaring it inside the loop not cause harm to memory and performance?

+6  A: 

Declaring it inside the loop won't cause any harm to the memory and performance.

missingfaktor
+4  A: 

If possible use List<BusinessObject> and Iterator<BusinessObject> to avoid casting:

List<BusinessObject> list = myObject.getList();
Iterator<BusinessObject> itr = list.iterator();

while (itr.hasNext()) {
   process(itr.next());
}
cyborg
That of course only works in 1.5 and higher. Not everyone is so fortunate :)
extraneon
+5  A: 

One principle of good software design is to limit the scope of local variables, i.e. to declare them just in time within a block that ends soon after the last use of that variable. This doesn't affect performance or other "hard" aspects but makes the program more readable and easier to analyze.

In summary, doing what you're doing is considered GOOD.

Carl Smotricz
+1  A: 

myBo is simply a reference to an object (that is returned by itr.next()). As such the amount of memory that it needs is very small and allocating/deallocating it should not affect your program significantly. IMO, declaring it inside the loop where it is used actually helps make it more readable.

MAK
+1  A: 

If short -- no. In C++ it could be a problem if myBo is created by copying but in Java there is always used references, is'nt it?
for performance, its better to optimize something you are do in process()

A: 

The temporary reference myBo is put on stack and should mostly be optimized away. There shouldn't be any performance penalty in your code.

bryantsai
+4  A: 

The most elegant solution for your loop would be an enhanced for loop (java 5 or newer):

List<BusinessObject> list = myObject.getList();

for( BusinessObject myBo : list ) {
    process(myBo);
}

But even with the code you provided there will be no performance problem, because all the temporary variables only hold references to the BusinessObject, which is very cheap.

tangens
+2  A: 

It doesn't cause any memory harm.

BTW unless you're omitting some code you may skip the declaration altogether:

while (itr.hasNext()){
    //BusinessObject myBo=(BusinessObject)itr.next();
    process((BusinessObject)itr.next());
} 
OscarRyz