How much memory is allocated for different data types in Javascript and Python?
In case Python 3
, examine the amount of storage that each of the major data types consumes,
First sizeof
, let's define a helper function to help us explore,
import sys
def sizeof(x):
print(x.__class__, sys.getsizeof(x), x)
Running this with 64 bit Python 3.6.1, here are the results:
>>> sizeof(None)
<class 'NoneType'> 16 None
None
takes 16 bytes. Then consider the integers,
>>> sizeof(10)
<class 'int'> 28 10
>>> sizeof(2**64)
<class 'int'> 36 18446744073709551616
>>> sizeof(2**128)
<class 'int'> 44 340282366920938463463374607431768211456
Integers in python are arbitrary precision, and the behavior above rightfully manifests itself, the size grows linearly in the logarithm of an integer.
>>> sizeof(0.0)
<class 'float'> 24 0.0
>>> sizeof(10.0**100)
<class 'float'> 24 1e+100
>>> sizeof(10.0**308)
<class 'float'> 24 1e+308
Floats in python seem to be of constant size (24 bytes)!
>>> sizeof("")
<class 'str'> 49
>>> sizeof("A")
<class 'str'> 50 A
>>> sizeof("AB")
<class 'str'> 51 AB
>>> sizeof("ABC")
<class 'str'> 52 ABC
Empty string
is 49 bytes, it grows linearly with line length.
Next, consider lists, dicts, tuples and sets,
>>> sizeof([])
<class 'list'> 64 []
>>> sizeof([1,2,3,4,5,6,7,8,9,10])
<class 'list'> 144 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Empty list
takes 64 bytes, it grows with the number of elements.
>>> sizeof(())
<class 'tuple'> 48 ()
>>> sizeof((1,))
<class 'tuple'> 56 (1,)
>>> sizeof((1,2,3,4,5,6,7,8,9,10,))
<class 'tuple'> 128 (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Empty tuple
takes 48 bytes and grows with the number of elements.
>>> sizeof({})
<class 'dict'> 240 {}
>>> sizeof({"a" : 1})
<class 'dict'> 240 {'a': 1}
>>> a = {}
>>> for i in range(20):
... a[i] = i**2
...
>>> sizeof(a)
<class 'dict'> 648 {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225, 16: 256, 17: 289, 18: 324, 19: 361}
Empty dict
takes 240 bytes and grows with the number of elements.
>>> sizeof(set())
<class 'set'> 224 set()
>>> sizeof({1})
<class 'set'> 224 {1}
>>> sizeof({1,2,3,4,5,6,7,8,9,10})
<class 'set'> 736 {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Empty set
takes 224 bytes and grows with the number of elements.
This completes a brief exploration of memory consumption by various data types in python
. Memory management in Python is easy - if you just don't care, but it turns out to be a problem when scaling!
You read more about memory management in Python in the anano docs here .
source to share