对于 Netty ByteBuf 的零拷贝(Zero
Copy) 的理解
根据 Wiki 对 Zero-copy 的定义:
"Zero-copy" describes computer operations in which the CPU does not
perform the task of copying data from one memory area to another. This is
frequently used to save CPU cycles and memory bandwidth when transmitting
a file over a network.
即所谓的 Zero-copy, 就是在操作数据时, 不需要将数据 buffer 从⼀个内存区
域拷贝到另⼀个内存区域. 因为少了⼀次内存的拷贝, 因此 CPU 的效率就得
到的提升.
在 OS 层⾯上的 Zero-copy 通常指避免在 户态(User-space) 与 内核态
(Kernel-space) 之间来回拷贝数据. 例如 Linux 提供的 mmap 系统调⽤, 它可
以将⼀段⽤户空间内存映射到内核空间, 当映射成功后, ⽤户对这段内存区域
的修改可以直接反映到内核空间; 同样地, 内核空间对这段区域的修改也直接
反映⽤户空间. 正因为有这样的映射关系, 我们就不需要在 户态(User-
space) 与 内核态(Kernel-space) 之间拷贝数据, 提⾼了数据传输的效率.
⽽需要注意的是, Netty 中的 Zero-copy 与上⾯我们所提到到 OS 层⾯上的
Zero-copy 不太⼀样, Netty的 Zero-coyp 完全是在⽤户态(Java 层⾯)的, 它的
Zero-copy 的更多的是偏向于 优化数据操作 这样的概念.
Netty 的 Zero-copy 体现在如下⼏个个⽅⾯:
Netty 提供了 CompositeByteBuf 类, 它可以将多个 ByteBuf 合并为⼀个
逻辑上的 ByteBuf, 避免了各个 ByteBuf 之间的拷贝.
通过 wrap 操作, 我们可以将 byte[] 数组、ByteBuf、ByteBuffer等包装成
⼀个 Netty ByteBuf 对象, 进⽽避免了拷贝操作.
ByteBuf ⽀持 slice 操作, 因此可以将 ByteBuf 分解为多个共享同⼀个存储
区域的 ByteBuf, 避免了内存的拷贝.