I have a StringBuilder object that needs to be trimmed (i.e. all whitespace chars /u0020 and below removed from either end).
I can’t seem to find a method in string builder that would do this.
Here’s what I’m doing now:
String trimmedStr = strBuilder.toString().trim();
This gives exactly the desired output, but it requires two Strings to be allocated instead of one. Is there a more efficient to trim the string while it’s still in the StringBuilder?
You should not use the deleteCharAt approach.
As Boris pointed out, the deleteCharAt method copies the array over every time. The code in the Java 5 that does this looks like this:
Of course, speculation alone is not enough to choose one method of optimization over another, so I decided to time the 3 approaches in this thread: the original, the delete approach, and the substring approach.
Here is the code I tested for the orignal:
The delete approach:
And the substring approach:
I performed 100 tests, each time generating a million-character StringBuffer with ten thousand trailing and leading spaces. The testing itself is very basic, but it gives a good idea of how long the methods take.
Here is the code to time the 3 approaches:
I got the following output:
As we see, the substring approach provides a very slight optimization over the original “two String” approach. However, the delete approach is extremely slow and should be avoided.
So to answer your question: you are fine trimming your StringBuilder the way you suggested in the question. The very slight optimization that the substring method offers probably does not justify the excess code.