I wanna read documents and process them. Each iteration processes one document.
Which kind of code is better?
1.
BufferedReader br;
for(File f : files)
{
br = new BufferedReader(......);
......
}
2.
for(File f : files)
{
BufferedReader br = new BufferedReader(......);
......
}
My point is which one is more efficient in terms of space and speed?
The latter is clearer in my view. In general, prefer to declare local variables with the smallest scope you can, ideally initializing them at the point of declaration.
It won't directly affect the performance - but it will affect readability and maintenance, which will affect the ease with which you can make changes which will affect performance.
In general:
In code optimization it is very easy to fall into the trap of Win Small, Lose Big: each individual method may be optimized to perfection, but overall system performance may still be a disaster due to the inadequacies of global architecture. One must always optimize top-down, and when doing so, you'll see that only 1% or less lines of code can actually contribute to overall performance if replaced by an optimized version.
If you don't use the br
variable elsewhere, they're both exactly the same.
Beware not to lose too much time attempting nano-optimizations. Even when the bytecode differs, the JIT isn't so bad when optimizing the obvious. You don't need to declare a variable before the block where it is used and you shouldn't as it make it less clear what it is used for.
The only difference is the br
is second case is local in scope to loop whereas in first case it can be accessed outside loop. But note that even in first case br
ref variable would be available outaide loop and not the values you gave it inside for loop.
Else they are just the same. Though the second case is more readable
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With