From 913cae6fef1f708238918cbdf3b25db03c805604 Mon Sep 17 00:00:00 2001 From: Dmitry Konstantinov Date: Tue, 24 Mar 2020 13:13:52 +0300 Subject: [PATCH] Optimize log2 in PoolThreadCache (#10128) Motivation: The current implementation of log2 in PoolThreadCache uses a loop and less efficient than an version based on Integer.numberOfLeadingZeros (intrinsic). Modifications: Replace the current log2 implementation in PoolThreadCache with a version based on Integer.numberOfLeadingZeros Result: It can improve performance slightly during allocation and de-allocation of ByteBuf using pooled allocator. --- .../src/main/java/io/netty/buffer/PoolThreadCache.java | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/buffer/src/main/java/io/netty/buffer/PoolThreadCache.java b/buffer/src/main/java/io/netty/buffer/PoolThreadCache.java index c1bf7e6d07..92e46a0f02 100644 --- a/buffer/src/main/java/io/netty/buffer/PoolThreadCache.java +++ b/buffer/src/main/java/io/netty/buffer/PoolThreadCache.java @@ -42,6 +42,7 @@ import java.util.concurrent.atomic.AtomicBoolean; final class PoolThreadCache { private static final InternalLogger logger = InternalLoggerFactory.getInstance(PoolThreadCache.class); + private static final int INTEGER_SIZE_MINUS_ONE = Integer.SIZE - 1; final PoolArena heapArena; final PoolArena directArena; @@ -151,13 +152,9 @@ final class PoolThreadCache { } } + // val > 0 private static int log2(int val) { - int res = 0; - while (val > 1) { - val >>= 1; - res++; - } - return res; + return INTEGER_SIZE_MINUS_ONE - Integer.numberOfLeadingZeros(val); } /** @@ -323,6 +320,7 @@ final class PoolThreadCache { private MemoryRegionCache cacheForNormal(PoolArena area, int normCapacity) { if (area.isDirect()) { + // sizeClass == Normal => normCapacity >= pageSize => the shifted value > 0 int idx = log2(normCapacity >> numShiftsNormalDirect); return cache(normalDirectCaches, idx); }