File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Performance and the fly likes good place to declare variable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Performance
Bookmark "good place to declare variable" Watch "good place to declare variable" New topic

good place to declare variable

Hendra Kurniawan
Ranch Hand

Joined: Jan 31, 2011
Posts: 239
Which one is better?


which is better for performance, which is better for memory? or even better, which is better for both? or no difference at all?
Jeff Verdegan

Joined: Jan 03, 2004
Posts: 6109

It makes no difference at all. All of a method's local variables are allocated at once, on method entry.

Good programming style dictates that we declare the variable in the smallest scope in which it is used, and also that we don't initialize to a value at declaration unless that value is actually meaningful and expected to be used in our method.

So in your case, even if you declared outside the loop, you'd skip the = null part, since there's no meaning or reason for it. However, since you're only using the variable inside the loop, you should declare it inside the loop anyway, so that becomes a moot point.
Deepak Bala

Joined: Feb 24, 2006
Posts: 6662

What Jeff said

which is better for performance ?


which is better for memory?

Neither. Since you create objects anyway.

no difference at all?

Yes, no difference whatsoever.

SCJP 6 articles - SCJP 5/6 mock exams - More SCJP Mocks
Chris Hurst
Ranch Hand

Joined: Oct 26, 2003
Posts: 443

Seems the first one is better which is probably what most people would guess ;-)

Why the second doesn't have to null a local but I guess that was obvious ;-) a class member it would have had to.

- Would this give you a measurable improvement .. nope

I only did this for personal interest, I used a class viewer on similar code in Java 6 and one appears to have to null the variable and took two more lines of byte code, will the JIT just drop the difference ? / any impact on escape analysis ? Do we care ? ;-)

"Eagles may soar but weasels don't get sucked into jet engines" SCJP 1.6, SCWCD 1.4, SCJD 1.5,SCBCD 5
Winston Gutkowski

Joined: Mar 17, 2011
Posts: 8927

Hendra Kurniawan wrote:Which one is better?

The fact is, they're both crap.

Why? Because they simply create 2 billion objects for no apparent reason.

For any question like this to have any meaning, it's got to have some context; the words of Wulf (below).


Bats fly at night, 'cause they aren't we. And if we tried, we'd hit a tree -- Ogden Nash (or should've been).
Articles by Winston can be found here
I agree. Here's the link:
subject: good place to declare variable
It's not a secret anymore!