Search code examples
pythonobjectsize

Which python built-in object has the least size in memory?


# On Python 3.9.2
>>> sys.getsizeof(None)
16
>>> sys.getsizeof(0)
24
>>> sys.getsizeof(True)
28

I just wanted to know if there is any object with its size less than the size of None object, i.e. less than 16 bytes.


Solution

  • As suggested by @quamrana, I tried to sort all the built-in objects based on their sizes and got into the following observation. The code snippet I used:

    import builtins, sys, inspect
    
    classes = [i for i in builtins.__dict__.values() if inspect.isclass(i)]
    objects = []
    for i in classes:
        try:
            objects.append((i, sys.getsizeof(i())))
        except:
            ...
    objects.sort(key=lambda x: x[1])
    for i in objects[:10]:
        print(i)
    

    And the stdout for the above snippet is:

    (<class 'object'>, 16)
    (<class 'bool'>, 24)
    (<class 'float'>, 24)
    (<class 'int'>, 24)
    (<class 'complex'>, 32)
    (<class 'bytes'>, 33)
    (<class 'tuple'>, 40)
    (<class '_frozen_importlib.BuiltinImporter'>, 48)
    (<class 'str'>, 49)
    (<class 'bytearray'>, 56)
    

    These are the 10 objects which has least size on Python 3.9.2 which runs on my machine. As per @martineau's comment, the size of each object varies across different python versions and machines.