gpt4 book ai didi

java - buffer(int) 和 buffer() 有什么区别?

转载 作者:行者123 更新时间:2023-12-01 16:45:34 25 4
gpt4 key购买 nike

我正在尝试向客户端发送数据包,我注意到即使我没有设置初始容量,也没有错误。

// data is another ByteBuf object
// With capacity
ByteBuf d = Unpooled.buffer(2 + data.array().length);
d.writeByte(identifiers[0]).writeByte(identifiers[1]).writeBytes(data.array());
// Without capacity
ByteBuf d = Unpooled.buffer();
d.writeByte(identifiers[0]).writeByte(identifiers[1]).writeBytes(data.array());

这两者有什么区别吗?他们似乎都工作得很好。

我也想知道我做得是否正确,我正在使用Unpooled.buffer创建一个新的ByteBuf,在其中写入我的数据并将其发送到当我需要向客户端发送某些内容时,使用 channel.write(ByteBuf) 进行 channel 。我这样做对吗?

最佳答案

来自docs:

  • 缓冲区()

    creates a new big-endian Java heap buffer with reasonably small initial capacity, which expands its capacity boundlessly on demand.

  • 缓冲区(intinitialCapacity)

    creates a new big-endian Java heap buffer with the specified capacity, which expands its capacity boundlessly on demand. The new buffer's readerIndex and writerIndex are 0.

因此,buffer(int)buffer() 执行相同的操作,但具有指定的起始容量。如果您知道需要比默认容量更大的容量,它的性能会更好,因为如果没有足够的容量,它就不必继续扩展。 编辑:另外,正如 @yelliver 所说,您可以通过指定来节省内存,这可能会根据您创建的缓冲区对象数量(或缓冲区的大小)而增加。

看起来 buffer(int) 还设置了一些 buffer() 可能不会的索引。

关于java - buffer(int) 和 buffer() 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52120271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com