Skip to content

Commit aae1500

Browse files
committed
Grow buffer size by 2x when expanding
1 parent 6109c66 commit aae1500

1 file changed

Lines changed: 12 additions & 2 deletions

File tree

src/main/java/com/grack/nanojson/JsonTokener.java

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -766,8 +766,18 @@ void fixupAfterRawBufferRead() throws JsonParserException {
766766
private void expandBufferIfNeeded(int size) {
767767
if (reusableBuffer.remaining() < size) {
768768
int oldPos = reusableBuffer.position();
769-
int increment = Math.max(512, size - reusableBuffer.remaining());
770-
CharBuffer newBuffer = CharBuffer.allocate(reusableBuffer.capacity() + increment);
769+
int currentCap = reusableBuffer.capacity();
770+
int need = size - reusableBuffer.remaining();
771+
772+
// Grow exponentially to avoid repeatedly appending many
773+
// small increments on long strings. Ensure we always
774+
// grow at least by a modest chunk to avoid very small
775+
// resizes on tiny buffers.
776+
long doubled = (long) currentCap * 2;
777+
int minGrow = Math.max(512, need);
778+
int newCap = (int) Math.max(doubled, currentCap + minGrow);
779+
780+
CharBuffer newBuffer = CharBuffer.allocate(newCap);
771781
reusableBuffer.flip(); // position -> 0, limit -> oldPos
772782
newBuffer.put(reusableBuffer); // copy all existing data
773783
reusableBuffer = newBuffer;

0 commit comments

Comments
 (0)