StringBuilder.insert, delete and replace are fairly expensive operations since they have to shift the everything past that point to make room or squeeze up. With replace, if the replacement String is the same length as the one replaced, you don’t have this problem.
To find out how many chars are in a StringBuilder altready use length( );
To reuse a StringBuilder use setLength( 0 );
If you know the precise length of the String you are building in advance, usually you can build it more efficiently with a char[] ca and use new String( ca ) to convert the result.
| Effect of StringBuilder Optimising | |||
|---|---|---|---|
| Time Before Optimising | Time After Optimising | % improvement | |
| Sun | 27.5 sec | 24 sec | 13% |
| Jet | 25 sec | 22.5 sec | 10% |
StringBuilder is the usual choice, preferably with an high-side estimate of the
final length.
StringBuffer is for old JDKs.
StringWriter is for when you have code that was originally designed to write
files.
You can use a ByteArrayStream as a sort of StringBuilder for bytes.
You can get the compiler to do a number of optimisations with StringBuilder if you use the -XX:+OptimizeStringConcat javac compiler option.
|
|
You can get the freshest copy of this page from: | or possibly from your local J: drive (Java virtual drive/mindprod.com website mirror) |
| http://mindprod.com/jgloss/stringbuilder.html | J:\mindprod\jgloss\stringbuilder.html | |
![]() | Please email your feedback for publication,
letters to the editor, errors, omissions, typos, formatting errors, ambiguities, unclear wording,
broken/redirected link reports, suggestions to improve this page or comments to
Roedy Green :
| |
| Canadian Mind Products | ||
| mindprod.com IP:[65.110.21.43] | ||
| view Blog | Your face IP:[38.107.179.214] | |
| Feedback | You are visitor number 14,845. | |