• Post Reply Bookmark Topic Watch Topic
  • New Topic

"Clean" programming practice?  RSS feed

 
Phil Chuang
Ranch Hand
Posts: 251
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Say I have a bit of code like:

If output is the only thing that matters, and I don't want to make the code into a procedural method, should I do the following to keep memory "clean" ?

[ September 23, 2003: Message edited by: Phil Chuang ]
 
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
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.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!