From 1cc4607f07961622cfa3fb4351320ed54359be33 Mon Sep 17 00:00:00 2001 From: Scott Mitchell Date: Mon, 12 Jun 2017 10:46:30 -0700 Subject: [PATCH] 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. --- .../util/internal/AppendableCharSequence.java | 21 +++++-------------- 1 file changed, 5 insertions(+), 16 deletions(-) diff --git a/common/src/main/java/io/netty/util/internal/AppendableCharSequence.java b/common/src/main/java/io/netty/util/internal/AppendableCharSequence.java index 3d3373ec80..408c32f380 100644 --- a/common/src/main/java/io/netty/util/internal/AppendableCharSequence.java +++ b/common/src/main/java/io/netty/util/internal/AppendableCharSequence.java @@ -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 {