Skip to content

discardReadBytes() memory compaction

discardReadBytes() memory compaction is a mechanism in [[netty|Netty]]'s ByteBuf used to reclaim memory space occupied by data that has already been read^[600-developer__big-data__netty__netty-ByteBuf.md].

In the ByteBuf structure, the memory space between index 0 and readerIndex is referred to as discardable bytes^[600-developer__big-data__netty__netty-ByteBuf.md]. When readerIndex is greater than 0, it indicates that this preceding space holds data that has already been consumed.

Compaction Process

The discardReadBytes() method performs a compaction operation by moving the readable bytes within the buffer^[600-developer__big-data__netty__netty-ByteBuf.md]. This process removes the "discardable bytes" section located at the beginning of the buffer and shifts the remaining content to the front.

The internal state changes as follows^[600-developer__big-data__netty__netty-ByteBuf.md]:

  • Before: The buffer consists of discardable bytes, readable bytes (CONTENT), and writable bytes.
  • After: The readable bytes are shifted to the start of the buffer (index 0). The readerIndex is reset to 0, and the writerIndex is decreased by the number of discarded bytes.

Impact on Capacity

The primary benefit of this operation is that it increases the size of the writable bytes section at the end of the buffer without allocating new memory^[600-developer__big-data__netty__netty-ByteBuf.md]. By shifting the content, the space previously occupied by the read data is freed up and converted into writable space.

It is important to note that this operation involves copying memory (often implemented via Arrays.copyOf or similar mechanisms), which incurs a performance cost proportional to the number of readable bytes being moved^[600-developer__big-data__netty__netty-ByteBuf.md].

  • ByteBuf
  • [[Reader Index]]
  • [[Writer Index]]

Sources

^[600-developer__big-data__netty__netty-ByteBuf.md]