Alex Rivera | Logout

Declare an object inside or outside a loop?

Asked 2008-12-18T13:03:12.740
61

Is there any performance penalty for the following code snippet?

for (int i=0; i<someValue; i++)
{
    Object o = someList.get(i);
    o.doSomething;
}

Or does this code actually make more sense?

Object o;
for (int i=0; i<someValue; i++)
{
    o = someList.get(i);
    o.doSomething;
}

If in byte code these two are totally equivalent then obviously the first method looks better in terms of style, but I want to make sure this is the case.

Edit
Report

2 Answers

1

These have different semantics. Which is more meaningful?

Reusing an object for "performance reasons" is often wrong.

The question is what does the object "mean"? WHy are you creating it? What does it represent? Objects must parallel real-world things. Things are created, undergo state changes, and report their states for reasons.

What are those reasons? How does your object model and reflect those reasons?

answered 2008-12-18T13:10:13.227
0

When using multiple threads (if your doing 50+) then i found this to be a very effective way of handling ghost thread problems:

Object one;
Object two;
Object three;
Object four;
Object five;
try{
for (int i=0; i<someValue; i++)
{
o = someList.get(i);
o.doSomething;
}
}catch(e){
e.printstacktrace
}
finally{
one = null;
two = null;
three = null;
four = null;
five = null;
System.gc();
}
answered 2013-07-29T20:50:15.223

Your Answer