views:

1707

answers:

15

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.

+18  A: 

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.

Dave Markle
Also it prevents namespace polution...
EricSchaefer
+1  A: 

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.

Will Mc
A: 

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.

Jack Ryan
With respect, I think you may have that flipped around. It's the former that keeps the variable in the scope in which it is used.
Will Wagner
-1: "makes sense" depends on what the program is supposed to "mean". Objects exist for a reason. What is that reason?
S.Lott
Will you were right I had flipped it around. Fixed now. S. Lott: in this example I think it is obvious that the object exists to hold a value that is got from a list. It serves no purpose outside the loop.
Jack Ryan
+4  A: 

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.

Mehrdad Afshari
I am not sure about allocation pattern you describe. Consider this code:if (flag) {char buffer[100];...} else {char buffer[2000];...}IN this case it would be really dumb for teh compiler to allocate all memory in advance. Doubly so if the stack is at a premium (embedded apps).
Arkadiy
Smart compilers usually allocate it by finding the maximum unshared memory in every code path. In your example, it's 2000 bytes which they allocate. If you didn't use it, it's not really costly, since it's just add esp, 2000 instead of add esp, 200.
Mehrdad Afshari
+1  A: 

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?

S.Lott
There is no reuse of objects going on in those two snippets at all, just reuse of reference variables.
Ilja Preuß
A reference is -- to my mind -- an object, first class, the real deal. Where it's declared and how it's declared reflects the meaning, purpose and intent behind the object.
S.Lott
It might be the same conceptually, but it's a very different beast in Java and confusing references and objects has slowed down many, many beginners in their understanding.
Joachim Sauer
@saua: True. As shown in this case of moving the reference declaration around randomly as an "optimization".
S.Lott
+7  A: 

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.

Marco Tolk
+3  A: 

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?

Paul Mitchell
o will not be eligible for garbage collection intil it is removed from the list as well!
vickirk
+5  A: 

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.

Rolf Rander
It won't be identical in a larger method; the valid scope of the variable is recorded in the local variable table.
erickson
A: 

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.

Lonzo
+10  A: 

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 outide 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...

Dan Vinton
+2  A: 

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.

SamBeran
A: 

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!

Fortyrunner
+1  A: 

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

Scott Stanchfield
A: 

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.

Max
There is no constructor call here, the instance is obtained form a list
vickirk
A: 

Check this related discussion

Soumyadip