Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

good place to declare variable

 
Hendra Kurniawan
Ranch Hand
Posts: 239
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6109
6
Android IntelliJ IDE Java
  • Likes 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6663
5
Firefox Browser Linux MyEclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Chris Hurst
Ranch Hand
Posts: 443
3
C++ Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ? ;-)

 
Winston Gutkowski
Bartender
Pie
Posts: 10234
58
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic