Python-data storage format that saves memory space: bytes and encoding conversion

Recently, I am using the python-based MCU pyboard, so I will consider the memory of the MCU and hope to use a data storage format that can save memory space, so related research has been carried out.

Python built-in functions__sizeof__()

Through _, _sizeof__()you can check the memory of variables, print out the memory conditions of different encoding formats, and compare better encoding formats.

This method returns the amount of internal space (in bytes) occupied by the given object.

Python's available built-in encoding formats

Convert directly to bytes form:

  • "utf-8"
  • "gb2312"

Converted to byte array form:

  • bytearray

Students who want to learn more about these encoding formats can read the reference article at the end of the article.

compare results

Insert picture description here

in conclusion

  • String It
    can be found that for strings , encoding can indeed reduce the memory size of data. At the same time, the gb2312encoding format can reduce more memory usage. utf-8Secondly, the gb2312 format can be used to encode and transmit strings in pyb, which can improve program execution speed and reduce memory usage.
  • Numbers
    For numbers, python itself has compressed the memory footprint to a minimum, without optimization.
  • Lists and tuples
    Among tuples and lists, tuples are more space-saving. It is recommended to use tuples for data transmission when there is no need to change member variables.

Reference article:

Guess you like

Origin blog.csdn.net/qq_45779334/article/details/112793225