TrainBeaser for iPhone
The moose likes Java in General and the fly likes StringBuffer question Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "StringBuffer question" Watch "StringBuffer question" New topic
Author

StringBuffer question

Robert Paris
Ranch Hand

Joined: Jul 28, 2002
Posts: 585
I'm wondering whether I should make a new StringBuffer for every area where i do some appending, or make one and just call .delete( 0, buffer.size() - 1). Which makes better sense performance-wise?
Hari Gangadharan
Ranch Hand

Joined: Mar 08, 2001
Posts: 73
According to my experience, it is better to create a new one. Some people may say that the construction of a new object may degrade the performance. I write batch Java programs that goes against millions of records. I have not seen any significant preformance differences by creating a new object instead of reusing the objects. I have not done any performance evaluation on StringBuffer, but have done some using some other classes.


<B>Hari Gangadharan</B><BR>Unix is user friendly..<BR>but it chooses to whom it is friendly with!
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
There's another possibility: When you create the StringBuffer give it an initial capacity that is large enough for your needs, and then call setLength( 0 ) on the string buffer when you want to reuse it. I think, but I am not sure, that the capacity of the StringBuffer is not affected by the setLength( 0 ).
Check it out...
-Barry


Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Peter den Haan
author
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
Robert, remember first rule of optimization.
StringBuffer is backed by a char[] array. When, after doing your manipulations, you turn the StringBuffer into a String (or substring), this String is backed by the same char[] array. Any change you're trying to make, including delete(), will cause the StringBuffer to create a copy of its backing char[] array so that the String can remain immutable.
Re-using the same StringBuffer has two consequences. First, the act of creating a new char[] array and copying in the old contents is not going to be any faster than creating a whole new StringBuffer; with large strings, it might be slower. Second, because the char[] array can only grow, the String objects you create will be backed by oversized char[] arrays and memory consumption will be higher than necessary.
Bottom line is: don't.
- Peter
 
 
subject: StringBuffer question
 
Threads others viewed
storing a file
Adding nulls to stringbuffers
need help with stringbuffer
Does StringBuffer overrides equals()!!
StringBuffer does not have replaceAll
MyEclipse, The Clear Choice