As you know, in the second piece of code, the InputStream, the BufferedReader, and the char all become eligible for garbage collection as soon as the block terminates, whereas in the first excerpt, they say "live" until the end of the containing method. Is this a good idea? It depends. If the next thing in the containing method is a while(true) loop that runs for a long time, then it may be worth the effort to save memory. If the containing method will itself return shortly, then it's not worth it. As a general rule, don't worry about stuff like this unless it either becomes an observable problem, or you see a real reason why it could realistically become a problem. Otherwise, stick to making your code straightforward, simple and clear.
Incidentally, the BufferedReader really isn't adding any benefit to the system here. You've already got the benefits of a buffer, your char array, and you're not using the ever-popular readLine() method here, so the BufferedReader has nothing much to do. As for the sTringBuffer - even if you think there might be a reason to keep the StringBuffer around longer, so that you can use it in some other part of the program, it's seldom very beneficial. The standard StringBuffer class has been optimized so that the first time you call toString(), it's very fast, but if you make further alterations to the StringBuffer after that, they take longer. It's very nearly the same as if you'd actually reallocated a whole new StringBuffer. And in fact this is usually what you'd be better off doing, just for clarity, since saving the old StringBuffer doesn't really buy you any performance benefits. I'd minimize the scope of the StringBuffer to make it easier for GC to do its job. Here's my recommendation:
The whole point of the StringBuffer here is to create a String. Once that's done, you might as well let GC take it, since it won't really benefit you to saving it, and you might just make it harder for GC to find and reclaim it later.
"I'm not back." - Bill Harding, Twister
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop