• Post Reply Bookmark Topic Watch Topic
  • New Topic

Alternative to StringBuffer

 
Chethan C Gowda
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello All,

I am using StringBuffer to append large XML file (>2MB). StringBuffer is degrading the performace as well as I am running short of memory.
Can any one please suggest how to overcome this problem.
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Increase the amount of memory available to your program? See the JVM options available to do this.
 
Nitesh Kant
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
StringBuilder is supposed to be a better performing version of StringBuffer but unlike StringBuffer, it is not thread-safe.
This is what javadoc has to say:

This class provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

[ April 21, 2008: Message edited by: Nitesh Kant ]
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13078
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If this was my problem I would simply create the StringBuffer (or StringBuilder) with an initial size well in excess of the needed capacity. If you use the default size, StringBuffer will be automatically expanding in small jumps, creating many many extra objects and consuming lots of time.

Bill
 
Jimmy Clark
Ranch Hand
Posts: 2187
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Reduce the size of the "XML file". Or, in other words, break it up into chunks and process the XML chunks instead of one large >2MB data .

Search on "Chunking XML"
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, 2 MB doesn't sound all that big to me. But if you're appending to a file, why do you need a StringBuffer (or StringBuilder) at all? You can just use a BufferedWriter wrapped in a FileWriter, in append mode. Just write the data directly to the file. Well, using a BufferedWriter means it's not quite direct, but that's a minor point. You'll store some of the data in memory for a while before writing it, but the buffer size can be much less than 2 MG if that's a problem.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!