• Post Reply Bookmark Topic Watch Topic
  • New Topic

Variable declaration  RSS feed

 
PN Kumar
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One of the theories related to variable declaration suggests that it would be better to declare variables outside of loops to prevent multiple declarations. This would mean that we extend the scope of objects beyond the loop - thus postponing their garbage collection. In this case wouldn't this hamper the heap space available and thus affect performance?
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First, local variables (variables declared in a method) are allocated on the Java stack, not the heap. Second, regardless of the lexical scope of a variable in Java code, in the compiled bytecode, a local variable's scope generally extends for the entire method -- i.e., the stack doesn't grow and shrink as nested blocks are entered and exited. So this "one theory" of which you speak is completely groundless.
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another reason can be application performance.
If you need an Object inside a loop and you need only one of them (for some temporary storage or short-duration calculations for example) it's a waste of resources to create a new Object for every iteration of the loop.
For example

is likely to be a lot faster than

now if you needed the objects itself outside the loop you'd need to do the initialisation during each iteration of course

[ February 06, 2004: Message edited by: Jeroen Wenting ]
 
PN Kumar
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your replies.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!