Buffer has two main functions: first, improve transmission efficiency. Second, solve the problem of speed mismatch.
1. Improve Transmission Efficiency
The buffer reduces the number of data transfers by increasing the volume of data transmitted at a time, thus improving the data transmission efficiency. I/O knowledge is required for how to reduce the number of data transfers to improve efficiency.
The following Java code demonstrates the time consumed to output the same data when a buffer is used and when no buffer is used:
int count=1000000;FileOutputStream out = new FileOutputStream("D:\\work\\leen.txt");BufferedOutputStream bufferedOut= new BufferedOutputStream (new FileOutputStream("D:\\work\\lyq.txt"));long time=System.currentTimeMillis();for (int i = 0; i <count ; i++)out.write("Hello\r\n".getBytes());time=System.currentTimeMillis()-time;System.out.println("FileOutputStream writing time:"+time+"ms");time=System.currentTimeMillis();for (int i = 0; i <count ; i++)bufferedOut.write("Hello\r\n".getBytes());bufferedOut.flush();time=System.currentTimeMillis()-time;System.out.println("BufferedOutputStream writing time:"+time+"ms");
The output result on my computer is:
FileOutputStream writing time:2062msBufferedOutputStream writing time:158ms
It can be seen that the performance improvement caused by using the buffer zone is obvious.
2. Solve the Problem of speed Mismatch
Here is an example of an operating system.
The processing speed mismatch between the peripheral device and the CPU exists objectively. For example, when a computer process outputs a large volume of data to the printer for printing, the CPU output speed is much higher than the printer's printing speed, so the CPU has to stop and wait. On the contrary, when computer processes perform computation, the printer is idle because there is no data output. (Reference from computer operating system tutorial
After the buffer zone is introduced, the CPU writes the data to be transmitted to the peripherals to the buffer zone, and then executes other tasks so that the peripherals can slowly fetch data from the buffer.