• Post Reply Bookmark Topic Watch Topic
  • New Topic

separate printwriter calls versus constructed stringbuffer

 
Mike Ottinger
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, this is a simple question. What's better performance-wise, calling separate PrintWriter println methods or constructing the string from a StringBuffer object and printing that once? I'm imagining the second option is better. Have I answered my own question?
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, when dealing with I/O (input/output) calls, fewer calls with larger chunks is generally going to perform better. For this very reason there are buffered I/O classes in java.io like BufferedWriter. It takes care of buffering your small chunks into larger ones, calling the underlying stream only when it has a large chunk ready (or when you call flush() of course).
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To be more precise, fewer *disk access* is better. the java.io.Buffered* classes are doing exactly that - minimizing disc access.

So you should simply put a BufferedWriter between your PrintWriter and the inner Writer. No need for StringBuffers.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!