woshidan's loose leaf

ぼんやり勉強しています

InputStreamをBufferedInputStreamでラッピングする

HTTPUrlConnectionについて調べていたら、レスポンスボディの読み込みのところで、

InputStream in = new BufferedInputStream(urlConnection.getInputStream());

のようにurlConnection.getInputStream()BufferedInputStreamクラスのインスタンスでラップしてあって、 BufferedInputStreamの項を見てみたら、

Wraps an existing InputStream and buffers the input. Expensive interaction with the underlying input stream is minimized, since most (smaller) requests can be satisfied by accessing the buffer alone. The drawback is that some extra space is required to hold the buffer and that copying takes place when filling that buffer, but this is usually outweighed by the performance benefits.

と書いてあったのだけれど、書いてある意味がいまいちよく分からなかったので、 もう少しググって、以下の記事を見たら、

記事
http://www.atmarkit.co.jp/ait/articles/0709/12/news124_2.html

このようにバッファリング付きのバイト入力ストリームにすることにより、readメソッドを呼び出すごとにOSのファイル読み込みが実行されることを、防ぐことができます。

と書いてあって、一旦バッファに読み込んでから、バッファからプログラムの変数へ読み込んでいるんだな、 という感じに理解できてよかった。

言語のread命令だと、OSのファイルシステムなどファイルの取得元まで命令が飛ぶことがあるんだー、 プロセス間通信になるんか(この使い方で合ってるのだろうか)ー、という感じだった。