Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Declare variable in a loop - Good practice?

 
James Gordon
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Should I always use Method B or it doesn't really matter?

Method A
--------
for (int i=0; i<j; i++) {
int aNumber = i;
}
Method B
--------
int aNumber = 0;
for (int i=0; i<j; i++) {
aNumber = i;
}
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you need the variable after the loop has finished, then you had better declare it before the loop. Otherwise it disappears when the loop is exited.
-Barry
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Barry Gaunt:
If you need the variable after the loop has finished, then you had better declare it before the loop. Otherwise it disappears when the loop is exited.
-Barry

Quite correct!
And if you don't need the variable outside the loop, I think it is good practice to declare it inside the loop...
See http://www.refactoring.com/catalog/reduceScopeOfVariable.html and http://www.refactoring.com/catalog/replaceAssignmentWithInitialization.html
 
James Gordon
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Thanks for the response.
I was with the impression that declaring variables outsite a loop is always better since it saves the memory usage ... guess I am actually wrong all this while ...
 
Jamie Robertson
Ranch Hand
Posts: 1879
MySQL Database Suse
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In general, write the code that makes the makes the most sense when reading/writing it. I say this for 3 reasons:

1. with all the "smart" compiler and JIT run-time optimizations that happen after you write your code, it will probably execute the same code regardless of how it is typed in.
2. If you feel that the complete application you write does not meet speed specifications, then try to optimize the code for speed with the help of a profiling tool. You'll probably find other places where the code is causing the slow down, other than creation of a primitive in a loop.
3. highly optimized code is not always intuitively obvious, readable or maintainable.
So, as Ilja always says, The first rule of code optimization is DON'T!
Jamie
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jamie Robertson:
So, as Ilja always says, The first rule of code optimization is DON'T!

YEAH! Thanks for assisting...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic