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?
myBois 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 only created once, and adding it inside the loop should not affect your program. IMO, declaring it inside the loop where it is used actually helps make it more readable.