Should I always wrap an InputStream as BufferedInputStream?

前端 未结 4 2181
感情败类
感情败类 2020-12-08 07:28

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:



        
4条回答
  •  醉酒成梦
    2020-12-08 07:46

    Does it make sense to always wrap an InputStream as BufferedInputStream, when I know whether the given InputStream is something other than buffered?

    No.

    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.

    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.

    (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.)

提交回复
热议问题