Possible performance improvement for AbstractStringBuilder

I've been doing tests with Java StringBuilder, especially with the replacement (int, int, String) which is implemented in the AbstractStringBuilder class like this:

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)

    System.arraycopy(value, end, value, start + len, count - end);
    str.getChars(value, start);
    count = newCount;
    return this;


The call to the Arraycopy function "moves" parts of the contents of the character array of values ​​to make room for subsequent nested contents of str (str.getChars (value, start)). From my point of view, one only needs to do this arraycopy if the string length does not match the space that will be overwritten in the character array.

It is obviously very desperate to consider this performance issue, although tests with large character arrays (> 500k characters) and arraycopy in the StringBuilder replacement class resulted in measurable performance improvements.

Tested with java 6 on Windows 32bit platform on the same StringBuilder instance for a million replacement calls.

Do you think it is unimportant, a bug or am I missing something?


source to share

1 answer

I would pass it as a request for improvement.

Something like

if (end != start + len)
    System.arraycopy(value, end, value, start + len, count - end);


A further improvement would be to modify the copy of the array.

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);




All Articles