Skip to content

Commit bc71b09

Browse files
committed
Ensure exponential growth of container size
This makes it so that even for long strings the parse time is O(n) amortized instead of O(n²)
1 parent c7a6c1c commit bc71b09

1 file changed

Lines changed: 10 additions & 1 deletion

File tree

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

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -762,7 +762,16 @@ void fixupAfterRawBufferRead() throws JsonParserException {
762762
private void expandBufferIfNeeded(int size) {
763763
if (reusableBuffer.remaining() < size) {
764764
int oldPos = reusableBuffer.position();
765-
int increment = Math.max(512, size - reusableBuffer.remaining());
765+
int increment = Math.max(
766+
// don't reallocate too small parts
767+
512,
768+
Math.max(
769+
// allocate at least as much as needed
770+
size - reusableBuffer.remaining(),
771+
// ensure exponential growth so that it's O(n) amortized
772+
(int) (reusableBuffer.capacity() * 0.3)
773+
)
774+
);
766775
CharBuffer newBuffer = CharBuffer.allocate(reusableBuffer.capacity() + increment);
767776
reusableBuffer.flip(); // position -> 0, limit -> oldPos
768777
newBuffer.put(reusableBuffer); // copy all existing data

0 commit comments

Comments
 (0)