I wanted to know how much memory does different data types take up in Python and Javascript.I know that you do not need to declare types in both the languages but don't forget they are dynamically typed languages
For the case of Python 3, let's explore the the amount of storage each of the basic data types consume,
First, let's define a helper function sizeof which will 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. Next let's explore 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 above rightfully exhibits the behaviour, the size grows linearly in the logarithm of the integer represented.
>>> 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 appear 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
An empty string is 49 bytes, it grows linearly with the length of the string.
Next, lets explore lists, dicts, tuples & 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]
An empty list occupies 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)
An empty tuple occupies 48 bytes, it 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}
An empty dict occupies 240 bytes, it 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}
An empty set occupies 224 bytes, it grows with the number of elements.
This concludes my brief exploration on the memory consumption of various data types in python. Memory management in Python is easy—if you just don’t care but it proves to be challenge when you scale !
You read more on memory management in Python in the theano docs here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With