From 83db2b07b46d6096c9963c87d2530155dba06d58 Mon Sep 17 00:00:00 2001 From: Norman Maurer Date: Wed, 5 Jul 2017 10:21:22 +0200 Subject: [PATCH] Also use realloc when shrink the buffer. Motivation: We should also use realloc when shrink the buffer to eliminate extra allocations / memory copies when possible. Modifications: Use realloc for expanding and shrinking when possible. Result: Less memory copies and allocations --- .../UnpooledUnsafeNoCleanerDirectByteBuf.java | 28 +++++++------------ 1 file changed, 10 insertions(+), 18 deletions(-) diff --git a/buffer/src/main/java/io/netty/buffer/UnpooledUnsafeNoCleanerDirectByteBuf.java b/buffer/src/main/java/io/netty/buffer/UnpooledUnsafeNoCleanerDirectByteBuf.java index c343466dce..3b9c05b83b 100644 --- a/buffer/src/main/java/io/netty/buffer/UnpooledUnsafeNoCleanerDirectByteBuf.java +++ b/buffer/src/main/java/io/netty/buffer/UnpooledUnsafeNoCleanerDirectByteBuf.java @@ -43,31 +43,23 @@ class UnpooledUnsafeNoCleanerDirectByteBuf extends UnpooledUnsafeDirectByteBuf { public ByteBuf capacity(int newCapacity) { checkNewCapacity(newCapacity); - int readerIndex = readerIndex(); - int writerIndex = writerIndex(); int oldCapacity = capacity(); + if (newCapacity == oldCapacity) { + return this; + } - if (newCapacity > oldCapacity) { - ByteBuffer oldBuffer = buffer; - ByteBuffer newBuffer = reallocateDirect(oldBuffer, newCapacity); - setByteBuffer(newBuffer, false); - } else if (newCapacity < oldCapacity) { - ByteBuffer oldBuffer = buffer; - ByteBuffer newBuffer = allocateDirect(newCapacity); - if (readerIndex < newCapacity) { - if (writerIndex > newCapacity) { - writerIndex = newCapacity; - writerIndex(writerIndex); + ByteBuffer newBuffer = reallocateDirect(buffer, newCapacity); + + if (newCapacity < oldCapacity) { + if (readerIndex() < newCapacity) { + if (writerIndex() > newCapacity) { + writerIndex(newCapacity); } - oldBuffer.position(readerIndex).limit(writerIndex); - newBuffer.position(readerIndex).limit(writerIndex); - newBuffer.put(oldBuffer); - newBuffer.clear(); } else { setIndex(newCapacity, newCapacity); } - setByteBuffer(newBuffer, true); } + setByteBuffer(newBuffer, false); return this; } }