简体   繁体   English

BufferedInputStream 如何从 OS 请求数据块

[英]How BufferedInputStream requests data in chunks from OS

I read this question: Why is using BufferedInputStream to read a file byte by byte faster than using FileInputStream?我读了这个问题: 为什么使用 BufferedInputStream 逐字节读取文件比使用 FileInputStream 快? According to author BufferedInputStream(BIS) faster than FileInputStream(FIS) because when method read() is invoked in FileInputStream it always does system call using native API in order to fetch single byte, while BufferedInputStream does the same but it requires chunk of bytes from OS and stores them in local field called buf which is declared inside BIS class and then when read() is called BIS return byte from buf array.根据作者BufferedInputStream(BIS)FileInputStream(FIS) ) 快,因为当在FileInputStream中调用方法read()时,它总是使用本机 API 进行系统调用以获取单个字节,而BufferedInputStream执行相同操作但它需要来自操作系统并将它们存储在称为buf的本地字段中,该字段在 BIS class 中声明,然后当调用read()时,BIS 从buf数组返回字节。

I looked through the code of BIS,specifically read() method and it doesn't clear for me when it happens,when BIS requires chunk of bytes instead of one.我查看了 BIS 的代码,特别是read()方法,当 BIS 需要字节块而不是一个字节时,我不清楚它何时发生。 Method read() firstly checks if (pos >= count) If so it calls fill() method which firstly checks that buf is not full, if buf has space then method of InputStream is called public int read(byte b[], int off, int len) where b[] is our buffer, and inside of this method we can see that it makes system calls inside loop which is equal to len param.方法read()首先检查if (pos >= count)如果是,则调用fill()方法,首先检查 buf 是否已满,如果 buf 有空间,则 InputStream 的方法称为public int read(byte b[], int off, int len)其中 b[] 是我们的缓冲区,在这个方法内部我们可以看到它在等于len参数的循环内部进行系统调用。

for (; i < len ; i++) {
                c = read();

Did i miss something or both classes BIS and FIS will do the same amount of system calls in order to fetch each byte separately?我是否遗漏了什么,或者 BIS 和 FIS 两个类都会执行相同数量的系统调用以分别获取每个字节?

You are looking in the wrong place.你找错地方了。

InputStream provides implementation of int read(byte[] b, int off, int len) which indeed invokes read() in a loop. InputStream 提供了int read(byte[] b, int off, int len)的实现,它确实在循环中调用了read() So if a concrete InputStream wrapped by BuffredInputStream does not override this method, then there will be no performance improvement.所以如果一个被 BuffredInputStream 包裹的具体 InputStream 没有重写这个方法,那么就不会有性能提升。 However, the question you linked talks specifically about FileInputStream which does override this method by invoking native int readBytes(byte b[], int off, int len) .但是,您链接的问题专门讨论了 FileInputStream ,通过调用native int readBytes(byte b[], int off, int len)来覆盖此方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM