问题描述
当我知道给定的InputStream是否不是缓冲的时候,总是将InputStream包装为BufferedInputStream是否有意义?例如:
Does it make sense to always wrap an InputStream as BufferedInputStream, when I know whether the given InputStream is something other than buffered? For e.g:
InputStream is = API.getFromSomewhere()
if(!(is instanceof BufferedInputStream))
return new BufferedInputStream(is);
return is;
推荐答案
否。
如果您可能执行大量小读取(一次一个字节或几个字节),或者如果您想使用某些缓冲API提供的更高级功能;例如 BufferedReader.readLine()
方法。
It makes sense if you are likely to perform lots of small reads (one byte or a few bytes at a time), or if you want to use some of the higher level functionality offered by the buffered APIs; for example the BufferedReader.readLine()
method.
但是,如果你只是要执行大块读取使用读取(byte [])
和/或读取(byte [],int,int)
方法,包装 BufferedInputStream
中的 InputStream
没有帮助。
However, if you are only going to perform large block reads using the read(byte[])
and / or read(byte[], int, int)
methods, wrapping the InputStream
in a BufferedInputStream
does not help.
(针对@Peter Tillman对自己答案的评论,块读取用例肯定代表输入流的0.1%以上使用率
classes !!但是,在你不需要的时候,使用缓冲的API通常是无害的,这是正确的。)
(In response to @Peter Tillman's comment on his own Answer, the block read use-cases definitely represent more than 0.1% of uses of InputStream
classes!! However, he is correct in the sense that it is usually harmless to use a buffered API when you don't need to.)
这篇关于我应该总是将InputStream包装为BufferedInputStream吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!