Declare an object inside or outside a loop?

JavaPerformance

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

In today's compilers, no. I declare objects in the smallest scope I can, because it's a lot more readable for the next guy.

Solution 2 - Java

To quote Knuth, who may be quoting Hoare:

> Premature optimization is the root of all evil.

Whether the compiler will produce marginally faster code by defining the variable outside the loop is debatable, and I imagine it won't. I would guess it'll produce identical bytecode.

Compare this with the number of errors you'll likely prevent by correctly-scoping your variable using in-loop declaration...

Solution 3 - Java

There's no performance penalty for declaring the Object o within the loop. The compiler generates very similar bytecode and makes the correct optimizations.

See the article Myth - Defining loop variables inside the loop is bad for performance for a similar example.

Solution 4 - Java

You can disassemble the code with javap -c and check what the compiler actually emits. On my setup (java 1.5/mac compiled with eclipse), the bytecode for the loop is identical.

Solution 5 - Java

The first code is better as it restricts scope of o variable to the for block. From a performance perspective, it might not have any effects in Java, but it might have in lower level compilers. They might put the variable in a register if you do the first.

In fact, some people might think that if the compiler is dumb, the second snippet is better in terms of performance. This is what some instructor told me at the college and I laughed at him for this suggestion! Basically, compilers allocate memory on the stack for the local variables of a method just once at the start of the method (by adjusting the stack pointer) and release it at the end of method (again by adjusting the stack pointer, assuming it's not C++ or it doesn't have any destructors to be called). So all stack-based local variables in a method are allocated at once, no matter where they are declared and how much memory they require. Actually, if the compiler is dumb, there is no difference in terms of performance, but if it's smart enough, the first code can actually be better as it'll help the compiler understand the scope and the lifetime of the variable! By the way, if it's really smart, there should no absolutely no difference in performance as it infers the actual scope.

Construction of a object using new is totally different from just declaring it, of course.

I think readability is more important that performance and from a readability standpoint, the first code is definitely better.

Solution 6 - Java

I've got to admit I don't know java. But are these two equivalent? Are the object lifetimes the same? In the first example, I assume (not knowing java) that o will be eligible for garbage collection immediately the loop terminates.

But in the second example surely o won't be eligible for garbage collection until the outer scope (not shown) is exited?

Solution 7 - Java

Don't prematurely optimize. Better than either of these is:

for(Object o : someList) {
    o.doSomething();
}

because it eliminates boilerplate and clarifies intent.

Unless you are working on embedded systems, in which case all bets are off. Otherwise, don't try to outsmart the JVM.

Solution 8 - Java

I've always thought that most compilers these days are smart enough to do the latter option. Assuming that's the case, I would say the first one does look nicer as well. If the loop gets very large, there's no need to look all around for where o is declared.

Solution 9 - Java

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?

Solution 10 - Java

To get at the heart of this question... [Note that non-JVM implementations may do things differently if allowed by the JLS...]

First, keep in mind that the local variable "o" in the example is a pointer, not an actual object.

All local variables are allocated on the runtime stack in 4-byte slots. doubles and longs require two slots; other primitives and pointers take one. (Even booleans take a full slot)

A fixed runtime-stack size must be created for each method invocation. This size is determined by the maximum local variable "slots" needed at any given spot in the method.

In the above example, both versions of the code require the same maximum number of local variables for the method.

In both cases, the same bytecode will be generated, updating the same slot in the runtime stack.

In other words, no performance penalty at all.

HOWEVER, depending on the rest of the code in the method, the "declaration outside the loop" version might actually require a larger runtime stack allocation. For example, compare

for (...) { Object o = ... }
for (...) { Object o = ... }

with

Object o;
for (...) {  /* loop 1 */ }
for (...) { Object x =...; }

In the first example, both loops require the same runtime stack allocation.

In the second example, because "o" lives past the loop, "x" requires an additional runtime stack slot.

Hope this helps, -- Scott

Solution 11 - Java

The first makes far more sense. It keeps the variable in the scope that it is used in. and prevents values assigned in one iteration being used in a later iteration, this is more defensive.

The former is sometimes said to be more efficient but any reasonable compiler should be able to optimise it to be exactly the same as the latter.

Solution 12 - Java

In both cases the type info for the object o is determined at compile time.In the second instance, o is seen as being global to the for loop and in the first instance, the clever Java compiler knows that o will have to be available for as long as the loop lasts and hence will optimise the code in such a way that there wont be any respecification of o's type in each iteration. Hence, in both cases, specification of o's type will be done once which means the only performance difference would be in the scope of o. Obviously, a narrower scope always enhances performance, therefore to answer your question: no, there is no performance penalty for the first code snip; actually, this code snip is more optimised than the second.

In the second snip, o is being given unnecessary scope which, besides being a performance issue, can be also a security issue.

Solution 13 - Java

As someone who maintains more code than writes code.

Version 1 is much preferred - keeping scope as local as possible is essential for understanding. Its also easier to refactor this sort of code.

As discussed above - I doubt this would make any difference in efficiency. In fact I would argue that if the scope is more local a compiler may be able to do more with it!

Solution 14 - Java

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();
}

Solution 15 - Java

The answer depends partly on what the constructor does and what happens with the object after the loop, since that determines to a large extent how the code is optimized.

If the object is large or complex, absolutely declare it outside the loop. Otherwise, the people telling you not to prematurely optimize are right.

Solution 16 - Java

I've actually in front of me a code which looks like this:

for (int i = offset; i < offset + length; i++) {
    char append = (char) (data[i] & 0xFF);
    buffer.append(append);
}
...
for (int i = offset; i < offset + length; i++) {
    char append = (char) (data[i] & 0xFF);
    buffer.append(append);
}
...
for (int i = offset; i < offset + length; i++) {
    char append = (char) (data[i] & 0xFF);
    buffer.append(append);
}

So, relying on compiler abilities, I can assume there would be only one stack allocation for i and one for append. Then everything would be fine except the duplicated code.

As a side note, java applications are known to be slow. I never tried to do profiling in java but I guess the performance hit comes mostly from memory allocation management.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYuval AdamView Question on Stackoverflow
Solution 1 - JavaDave MarkleView Answer on Stackoverflow
Solution 2 - JavaDan VintonView Answer on Stackoverflow
Solution 3 - JavaMarco TolkView Answer on Stackoverflow
Solution 4 - JavaRolf RanderView Answer on Stackoverflow
Solution 5 - JavammxView Answer on Stackoverflow
Solution 6 - JavaPaul MitchellView Answer on Stackoverflow
Solution 7 - JavaSamBeranView Answer on Stackoverflow
Solution 8 - JavaWill McView Answer on Stackoverflow
Solution 9 - JavaS.LottView Answer on Stackoverflow
Solution 10 - JavaScott StanchfieldView Answer on Stackoverflow
Solution 11 - JavaJack RyanView Answer on Stackoverflow
Solution 12 - JavaLonzoView Answer on Stackoverflow
Solution 13 - JavaFortyrunnerView Answer on Stackoverflow
Solution 14 - JavaPetroView Answer on Stackoverflow
Solution 15 - JavaMaxView Answer on Stackoverflow
Solution 16 - JavaannoyedView Answer on Stackoverflow