| Author |
good place to declare variable
|
Hendra Kurniawan
Ranch Hand
Joined: Jan 31, 2011
Posts: 239
|
|
Which one is better?
or
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
Bartender
Joined: Jan 03, 2004
Posts: 5901
|
|
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
Bartender
Joined: Feb 24, 2006
Posts: 6592
|
|
What Jeff said
which is better for performance ?
Neither
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 - SCJP Mocks - SCJP 5 Mock exam (Word document ) - SCJP 5 Mock exam in Java.Inquisition format
|
 |
Chris Hurst
Ranch Hand
Joined: Oct 26, 2003
Posts: 370
|
|
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
Bartender
Joined: Mar 17, 2011
Posts: 4761
|
|
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; otherwise...read the words of Wulf (below).
Winston
|
Isn't it funny how there's always time and money enough to do it WRONG?
|
 |
 |
|
|
subject: good place to declare variable
|
|
|