AppendableCharSequence not to depend upon IndexOutOfBoundsException for resize

Motivation:
AppendableCharSequence depends upon IndexOutOfBoundsException to trigger a resize operation under the assumption that the resize operation will be rare if the initial size guess is good. However if the initial size guess is not good then the performance will be more unpredictable and likely suffer.

Modifications:
- Check the position in AppendableCharSequence#append to determine if a resize is necessary

Result:
More predictable performance in AppendableCharSequence#append.
This commit is contained in:
Scott Mitchell 2017-06-12 10:46:30 -07:00
parent 051e0ad4be
commit 1cc4607f07

View File

@ -68,12 +68,12 @@ public final class AppendableCharSequence implements CharSequence, Appendable {
@Override
public AppendableCharSequence append(char c) {
try {
chars[pos++] = c;
} catch (IndexOutOfBoundsException e) {
expand();
chars[pos - 1] = c;
if (pos == chars.length) {
char[] old = chars;
chars = new char[old.length << 1];
System.arraycopy(old, 0, chars, 0, old.length);
}
chars[pos++] = c;
return this;
}
@ -139,17 +139,6 @@ public final class AppendableCharSequence implements CharSequence, Appendable {
return new String(chars, start, end - start);
}
private void expand() {
char[] old = chars;
// double it
int len = old.length << 1;
if (len < 0) {
throw new IllegalStateException();
}
chars = new char[len];
System.arraycopy(old, 0, chars, 0, old.length);
}
private static char[] expand(char[] array, int neededSpace, int size) {
int newCapacity = array.length;
do {