Why is buffering in C++ important?

前端 未结 5 1172
离开以前
离开以前 2021-01-30 12:00

I tried to print Hello World 200,000 times and it took me forever, so I have to stop. But right after I add a char array to act as a buffer, it took le

5条回答
  •  情书的邮戳
    2021-01-30 12:09

    For the stand of file operations, writing to memory (RAM) is always faster than writing to the file on the disk directly.

    For illustration, let's define:

    • each write IO operation to a file on the disk costs 1 ms
    • each write IO operation to a file on the disk over a network costs 5 ms
    • each write IO operation to the memory costs 0.5 ms

    Let's say we have to write some data to a file 100 times.

    Case 1: Directly Writing to File On Disk

    100 times x 1 ms = 100 ms
    

    Case 2: Directly Writing to File On Disk Over Network

    100 times x 5 ms = 500 ms
    

    Case 3: Buffering in Memory before Writing to File on Disk

    (100 times x 0.5 ms) + 1 ms = 51 ms
    

    Case 4: Buffering in Memory before Writing to File on Disk Over Network

    (100 times x 0.5 ms) + 5 ms = 55 ms
    

    Conclusion

    Buffering in memory is always faster than direct operation. However if your system is low on memory and has to swap with page file, it'll be slow again. Thus you have to balance your IO operations between memory and disk/network.

提交回复
热议问题