数据报数据包上的 ByteBuffer 与 Buffer
我读到应该使用 ByteBuffer (java.nio) 代替 Buffer 类来读取数据,因为它更高效(?)。我的问题围绕一个 UDP 客户端,该客户端从多播地址读取数据包并将其处理为原始对象。从 DatagramSocket 解析这些数据包的最有效/最快的方法是什么?现在,我有一个数据报包,我将其字节数组包裹在 ByteBuffer 中并从那里读取。我的目标是最小化新对象的创建并最大化速度。
I've read that ByteBuffer (java.nio) should be used over the Buffer class for reading in data simply because it's more efficient (?). My question revolves around a UDP client that reads packets from a multicast address and processes them into primitive objects. What is the most efficient/fastest way to parse these packets from a DatagramSocket? Right now, I have a datagram packet whose byte array I wrap a ByteBuffer around and read from there. My goal is to minimize new object creation and maximize speed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
DatagramSocket
无法直接读入ByteBuffer
,但您可以使用DatagramChannel
代替。A
DatagramSocket
cannot read directly into aByteBuffer
, but you can do this using aDatagramChannel
instead.我认为使用 ByteBuffer 只是因为从程序员的角度来看 Buffer 没有足够的功能来提高访问效率,而不是从效率的角度来看。我怀疑效率是否存在差异,因为底层代码大多是重复的。
请注意,这是否比使用简单字节数组更有效并不总是很清楚——NIO 性能很容易被错误估计。
I think ByteBuffer is to be used just because Buffer does not have enough functionality to make access efficient from programmer's point of view, not from efficiency. I doubt there is difference in efficiency as underlying code is mostly duplicate.
Note tho that whether either is more efficient than using simple byte arrays is not always clear -- NIO performance is easy to misestimate.