file operation in binary vs text mode — performance concern

前端 未结 7 646
执笔经年
执笔经年 2020-12-31 10:04

In many projects, I saw that data object/structure are written into file in binary mode, and then retrieve them back from the file in binary mode again.

I wonder why

相关标签:
7条回答
  • 2020-12-31 10:37

    Binary is faster. Consider an integer stored in 32 bits (4 bytes), such as 123456. If you were to write this out as binary (which is how it is represented in the computer) it would take 4 bytes (ignoring padding between items for alignment in structures).

    To write the number as text, it has to be converted to a string of characters (some overhead to convert and memory to store) and then written it out, it will take at least 6 bytes as there are 6 characters to respresent the number. This is not including any additional padding such as spaces for alignment or delimiters to read/seperate the data.

    Now if you consider it you had several thousands of items, the additional time can add up and require more space, which would take longer to read in and then there is the additonal time to convert back to binary for storage after you have read the value into memory.

    The advantage to text, is that it is much easier to read for persons, rather then trying to read binary data or hex dumps of the data.

    0 讨论(0)
提交回复
热议问题