Java 中最好的可调整大小的字节缓冲区是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6329371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the best resizable byte buffer available in Java?
提问by Worker
I need a byte buffer class in Java for single-threaded use. The buffer should resize when it's full, rather than throw an exception or something. Very important issue for me is performance.
我需要一个用于单线程使用的 Java 字节缓冲区类。缓冲区应该在它满时调整大小,而不是抛出异常或其他东西。对我来说非常重要的问题是性能。
What would you recommend?
你会推荐什么?
ADDED: At the momement I use ByteBuffer but it cannot resize. I need one that can resize.
添加:目前我使用 ByteBuffer 但它无法调整大小。我需要一个可以调整大小的。
采纳答案by Nick Fortescue
Any reason not to use the boring normal ByteArrayOutputStream?
有什么理由不使用无聊的普通ByteArrayOutputStream吗?
As mentioned by miku above, Evan Jones gives a review of different typesand shows that it is very application dependent. So without knowing further details it is hard to speculate.
正如上面 miku 所提到的,Evan Jones 对不同类型进行了回顾,并表明它非常依赖于应用程序。因此,在不了解更多细节的情况下,很难进行推测。
I would start with ByteArrayOutputStream, and only if profiling shows it is your performance bottleneck move to something else. Often when you believe the buffer code is the bottleneck, it will actually be network or other IO - wait until profiling shows you need an optimisation before wasting time finding a replacement.
我会从 ByteArrayOutputStream 开始,并且只有在分析显示它是您的性能瓶颈时才会转移到其他地方。通常,当您认为缓冲区代码是瓶颈时,它实际上是网络或其他 IO - 等到分析显示您需要优化,然后再浪费时间寻找替代品。
If you are moving to something else, then other factors you will need to think about:
如果您正在转向其他方面,那么您需要考虑其他因素:
- You have said you are using single threaded use, so BAOS's synchronization is not needed
- what is the buffer being filled by and fed into? If either end is already wired to use Java NIO, then using a direct ByteBufferis very efficient.
- Are you using a circular buffer or a plain linear buffer? If you are then the Ostermiller Utilsare pretty efficient, and GPL'd
- 你说你是单线程使用,所以不需要BAOS的同步
- 缓冲区由什么填充和输入?如果任一端已经连接到使用 Java NIO,那么使用直接的ByteBuffer是非常有效的。
- 您使用的是循环缓冲区还是普通的线性缓冲区?如果您是,那么Ostermiller Utils非常高效,并且是 GPL
回答by Peter Lawrey
You can use a direct ByteBuffer. Direct memory uses virtual memory to start with is only allocated to the application when it is used. i.e. the amount of main memory it uses re-sizes automagically.
您可以使用直接的 ByteBuffer。直接内存使用虚拟内存开始,仅在使用时分配给应用程序。即它使用的主内存量自动调整大小。
Create a direct ByteBuffer larger than you need and it will only consume what you use.
创建一个比您需要的更大的直接 ByteBuffer,它只会消耗您使用的内容。
回答by Syed_Adeel
you can also write manual code for checking the buffer content continously and if its full then make a new buffer of greater size and shift all the data in that new buffer.
您还可以编写手动代码来连续检查缓冲区内容,如果已满,则创建一个更大的新缓冲区并移动该新缓冲区中的所有数据。