一个简单的规则,当我应该使用Java NIO的直接缓冲区网络I / O? [英] A simple rule of when I should use direct buffers with Java NIO for network I/O?

查看:152
本文介绍了一个简单的规则,当我应该使用Java NIO的直接缓冲区网络I / O?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有自然礼物的人能以简单直接的方式解释复杂的事情吗?为了获得最佳性能,当我在使用Java NIO进行网络I / O时,应该使用直接ByteBuffers还是常规ByteBuffers?






例如:我应该读一个堆缓冲区并从那里解析它,做许多get()(逐字节)或者我应该把它读入一个直接缓冲区并从直接缓冲区解析?



为了获得最佳性能,当我使用Java NIO进行网络I / O时,应该使用直接ByteBuffers和普通ByteBuffers? p>

直接缓冲区有许多优点




  • 避免在Java和本机内存之间传递的数据的额外副本。

  • 如果重新使用,只有使用的页面变成真正的内存。这意味着你可以使他们比他们需要的更大,他们只浪费虚拟内存。

  • 您可以有效地访问本地字节顺序的多字节基元。 (基本上一个机器码指令)




如果我读入堆缓冲区并从那里解析,做许多get()(逐字节)或者我应该读它到一个直接缓冲区并从直接缓冲区解析?


你一次读一个字节,你可能没有多大的优势。但是,使用直接字节缓冲区,您可以一次读取2或4个字节,并一次有效地解析多个字节。


] [selectors]


如果你正在解析实时数据,我会避免使用选择器。我发现使用阻塞NIO或忙等待NIO可以给你最低的延迟性能(假设你有一个相对较少的连接数,例如高达20)


Can someone with the natural gift to explain complex things in an easy and straightforward way address this question? To acquire the best performance when should I use direct ByteBuffers versus regular ByteBuffers when doing network I/O with Java NIO?


For example: Should I read into a heap buffer and parse it from there, doing many get() (byte by byte) OR should I read it into a direct buffer and parse from the direct buffer?

解决方案

To acquire the best performance when should I use direct ByteBuffers versus regular ByteBuffers when doing network I/O with Java NIO?

Direct buffers have a number of advantages

  • The avoid an extra copy of data passed between Java and native memory.
  • If they are re-used, only the page used are turning into real memory. This means you can make them much larger than they need to me and they only waste virtual memory.
  • You can access multi-byte primitives in native byte order efficiently. (Basically one machine code instruction)

Should I read into a heap buffer and parse it from there, doing many get() (byte by byte) OR should I read it into a direct buffer and parse from the direct buffer?

If you are reading a byte at a time, you may not get much advantage. However, with a direct byte buffer you can read 2 or 4 bytes at a time and effectively parse multiple bytes at once.

[real time] [selectors]

If you are parsing real time data, I would avoid using selectors. I have found using blocking NIO or busy waiting NIO can give you the lowest latency performance (assuming you have a relatively small number of connections e.g. up to 20)

这篇关于一个简单的规则,当我应该使用Java NIO的直接缓冲区网络I / O?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆