Is it possible to make Python use less than 12 bytes for an int?
>>> x=int()
>>> x
0
>>> sys.getsizeof(x)
12
I am not a computer specialist but isn’t 12 bytes excessive?
The smallest int I want to store is 0, the largest int 147097614, so I shouldn’t really need more than 4 bytes.
(There is probably something I misunderstand here as I couldn’t find an answer anywhere on the net. Keep that in mind.)
In python,
ints are objects just like everything else. Because of that, there is a little extra overhead just associated with the fact that you’re using an object which has some associated meta-data.If you’re going to use lots of ints, and it makes sense to lay them out in an array-like structure, you should look into
numpy. Numpyndarrayobjects will have a little overhead associated with them for the various pieces of meta-data that the array objects keep track of, but the actual data is stored as the datatype you specify (e.g.numpy.int32for a 4-byte integer.)Thus, if you have:
The array will take only slightly more than
4*5000 = 20000bytes of your memory