I have a question about proper use of StringBuffers. According to the API documentation, when you don't really know how many characters are going to wind up in your StringBuffer, you can construct it a couple of ways. You can create an empty StringBuffer with an initial capacity of 16 characters: StringBuffer sb = new StringBuffer(); ..or you can create a StringBuffer with no characters and an intitial capacity specified by an integer: StringBuffer sb = new StringBuffer(1000); Now, if you know your going to need > 16 characters, but aren't sure what the exact amount's going to be, is it better (performance wise) to go ahead guesstimate an amount? What if you over-estimate? Like in my example above, what (if any thing) is the down side to creating it with an initial capacity of 1000 and only using half the characters? What if you under-estimate? Is that a bad thing? Everywhere that I've read about optimizing Java's performance mentions something about being extra careful with String manipulation. I'd like to know as much as possible the top things to look for in making my Java app's run as efficently as possible. The 20% that I can do to make 80% worth of difference. Thanks, Rick
Of course it is a trade off on how much you actually end up putting into the StringBuffer. If you initialize it to 1000 and end up using just 20 then you have damaged the performance by making the OS find that much space just to waste it. On the flip side, each time that StringBuffer has to bump up the size costs performance also. You know we have a WHOLE forum just for performance questions.
"JavaRanch, where the deer and the Certified play" - David O'Meara
Joined: Aug 17, 2001
Cindy, Thanks for the reply on my question. Unfortunately, for the programming assignment I have in front of me there's really no predicting the size of the StringBuffer; it will probably never exceed 3k, but may be as small as 12 characters. On average, I'll need at least a 1000 character capacity, so that's probably what I'll use as the initial size of the StringBuffer. I have another couple of questions pertaining to performance, but wasn't sure which forum to place them in. It seems to me that a lot of performance related material I've read about is also beginner-related material! I'll be sure to try to be more selective in where I post my questions. Thanks again, Rick <><
Joined: Sep 29, 2000
You are welcome to post them here, it is just that you might get a better QUALITY answer over there .
subject: StringBuffer and general performance questions