I was doing tests with the Java StringBuilder, especially the replace(int, int, String) function which is implemented in the AbstractStringBuilder class as followed:
public AbstractStringBuilder replace(int start, int end, String str) {
if (start < 0)
throw new StringIndexOutOfBoundsException(start);
if (start > count)
throw new StringIndexOutOfBoundsException("start > length()");
if (start > end)
throw new StringIndexOutOfBoundsException("start > end");
if (end > count)
end = count;
int len = str.length();
int newCount = count + len - (end - start);
if (newCount > value.length)
expandCapacity(newCount);
System.arraycopy(value, end, value, start + len, count - end);
str.getChars(value, start);
count = newCount;
return this;
}
The Arraycopy function call does "move" parts the content of the value character array to make space for the later injected str content (str.getChars(value, start)). From my point of view, one should only do this arraycopy if the str length does not match the space to be overwritten in the character array anyways.
Clearly one is very desperate to consider this a performance issue, though making tests with bigger character arrays (>500k chars) and arraycopy in a StringBuilder replacement class leaded to measurable performance improvement.
Tested with java 6 on a Windows 32bit Platform an the same StringBuilder instance for some million replace calls.
Would you consider this to be unimportant, a bug or am I missing something completely?
I would pass it as a request for enhancement.
Something like
if (end != start + len)
System.arraycopy(value, end, value, start + len, count - end);
A further enhancement would be to change array copy.
public static void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length) {
if (srcPos != destPos && length != 0)
arraycopy0(src, srcPos, dest, destPos, length);
}
private static native void arraycopy0(Object src, int srcPos,
Object dest, int destPos,
int length);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With