Why does the following work fine?
String str;
while (condition) {
str = calculateStr();
.....
}
But this one is said to be dangerou
If you don't need to use the str
after the while loop (scope related) then the second condition i.e.
while(condition){
String str = calculateStr();
.....
}
is better since if you define an object on the stack only if the condition
is true. I.e. use it if you need it
The str
variable will be available and reserved some space in memory even after while executed below code.
String str;
while(condition){
str = calculateStr();
.....
}
The str
variable will not be available and also the memory will be released which was allocated for str
variable in below code.
while(condition){
String str = calculateStr();
.....
}
If we followed the second one surely this will reduce our system memory and increase performance.
I think the best resource to answer your question would be the following post:
Difference between declaring variables before or in loop?
According to my understanding this thing would be language dependent. IIRC Java optimises this, so there isn't any difference, but JavaScript (for example) will do the whole memory allocation each time in the loop.In Java particularly I think the second would run faster when done profiling.
As many people have pointed out,
String str;
while(condition){
str = calculateStr();
.....
}
is NOT better than this:
while(condition){
String str = calculateStr();
.....
}
So don't declare variables outside their scopes if you are not reusing it...
Declaring objects in the smallest scope improve readability.
Performance doesn't matter for today's compilers.(in this scenario)
From a maintenance perspective, 2nd option is better.
Declare and initialize variables in the same place, in the narrowest scope possible.
As Donald Ervin Knuth told:
"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil"
i.e) situation where a programmer lets performance considerations affect the design of a piece of code. This can result in a design that is not as clean as it could have been or code that is incorrect, because the code is complicated by the optimization and the programmer is distracted by optimizing.
I think the size of the object matters as well. In one of my projects, we had declared and initialized a large two dimensional array that was making the application throw an out-of-memory exception. We moved the declaration out of the loop instead and cleared the array at the start of every iteration.