From 23601902abb35d681be569bd06f02e13f1c31a24 Mon Sep 17 00:00:00 2001 From: Francesco Nigro Date: Wed, 1 Sep 2021 17:48:26 +0200 Subject: [PATCH] O(1) buffer next capacity computation (#11641) Motivation: Enlarging buffers approaching 4 MiB size requires n iterations Modification: Use a single instruction to compute the next buffer capacity Result: Faster/Simpler calculateNewCapacity --- .../java/io/netty/buffer/AbstractByteBufAllocator.java | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/buffer/src/main/java/io/netty/buffer/AbstractByteBufAllocator.java b/buffer/src/main/java/io/netty/buffer/AbstractByteBufAllocator.java index 2d880a76ff..3aa05ae480 100644 --- a/buffer/src/main/java/io/netty/buffer/AbstractByteBufAllocator.java +++ b/buffer/src/main/java/io/netty/buffer/AbstractByteBufAllocator.java @@ -20,6 +20,7 @@ import static io.netty.util.internal.ObjectUtil.checkPositiveOrZero; import io.netty.util.ResourceLeakDetector; import io.netty.util.ResourceLeakTracker; +import io.netty.util.internal.MathUtil; import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.StringUtil; @@ -272,12 +273,8 @@ public abstract class AbstractByteBufAllocator implements ByteBufAllocator { return newCapacity; } - // Not over threshold. Double up to 4 MiB, starting from 64. - int newCapacity = 64; - while (newCapacity < minNewCapacity) { - newCapacity <<= 1; - } - + // 64 <= newCapacity is a power of 2 <= threshold + final int newCapacity = MathUtil.findNextPositivePowerOfTwo(Math.max(minNewCapacity, 64)); return Math.min(newCapacity, maxCapacity); } }