I want to re-use StringBuffer to avoid memory re-allocation. I tried to "clean" it with the delete() method. But it doesn't work - it seems that sometimes, for some unclear reasons it re-allocates memory while "cleaning." How can I get it working without memory re-allocation? I'm using JDK 1.3.1.
StringBuffer relies on System.arraycopy to do most of its array manipulation. Since System.arraycopy is a native method, you might run into some unexpected, platform-specific behavior while using it. For example, the documentation for System.arraycopy reads, in part, as follows:
"If the src and dst arguments refer to the same array object, then the copying is performed as if the components at positions srcOffset through srcOffset+length-1 were first copied to a temporary array with length components and then the contents of the temporary array were copied into positions dstOffset through dstOffset+length-1 of the destination array."
The delete method does, in fact, call System.arraycopy with the src and dst arguments referring to the same array object. Depending upon the native implementation of System.arraycopy, this could certainly lead to memory allocation activity.
To be certain that memory allocation activity is kept to a minimum, you could write your own class that uses a char array to store its data and uses your own algorithms to shift the contents of the array around. However, you should do some benchmarks to see if the performance hit moving away from the native implementation is worth it.
Dig Deeper on Topics Archive
Have a question for an expert?
Please add a title for your question
Get answers from a TechTarget expert on whatever's puzzling you.