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
This commit is contained in:
Norman Maurer 2017-07-05 10:21:22 +02:00
parent ec490b2a88
commit 83db2b07b4

View File

@ -43,31 +43,23 @@ class UnpooledUnsafeNoCleanerDirectByteBuf extends UnpooledUnsafeDirectByteBuf {
public ByteBuf capacity(int newCapacity) { public ByteBuf capacity(int newCapacity) {
checkNewCapacity(newCapacity); checkNewCapacity(newCapacity);
int readerIndex = readerIndex();
int writerIndex = writerIndex();
int oldCapacity = capacity(); int oldCapacity = capacity();
if (newCapacity == oldCapacity) {
return this;
}
if (newCapacity > oldCapacity) { ByteBuffer newBuffer = reallocateDirect(buffer, newCapacity);
ByteBuffer oldBuffer = buffer;
ByteBuffer newBuffer = reallocateDirect(oldBuffer, newCapacity); if (newCapacity < oldCapacity) {
setByteBuffer(newBuffer, false); if (readerIndex() < newCapacity) {
} else if (newCapacity < oldCapacity) { if (writerIndex() > newCapacity) {
ByteBuffer oldBuffer = buffer; writerIndex(newCapacity);
ByteBuffer newBuffer = allocateDirect(newCapacity);
if (readerIndex < newCapacity) {
if (writerIndex > newCapacity) {
writerIndex = newCapacity;
writerIndex(writerIndex);
} }
oldBuffer.position(readerIndex).limit(writerIndex);
newBuffer.position(readerIndex).limit(writerIndex);
newBuffer.put(oldBuffer);
newBuffer.clear();
} else { } else {
setIndex(newCapacity, newCapacity); setIndex(newCapacity, newCapacity);
} }
setByteBuffer(newBuffer, true);
} }
setByteBuffer(newBuffer, false);
return this; return this;
} }
} }