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
posted
0
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
posted
0
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
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