rpraj
rpraj

Reputation: 157

Memory management in Python

I'm new to python.To find the sizeof an integer i used getsizeof method available in sys module. It returns 24 bytes for integer and 34 bytes for char.

>>> sys.getsizeof(1)
24
>>> sys.getsizeof('a')
34

I feel this size (24 bytes or 34 bytes) is very large to hold an integer or char... I feel that memory is getting wasted much.. Could you please help me in understanding the concept behind this memory management in python.

Upvotes: 6

Views: 869

Answers (2)

Every time you define an object in Python, you’ll create a new object with a new identity.

But there are some exceptions for small integers (between -5 and 256) and small strings (interned strings, with a special length (usually less than 20 character)) which are singletons and have same id (actually one object with multiple pointer).

Examples: In [1]: L1 = [1, 2, 3]

In [2]: L2 = [1, 2, 3]

In [3]: id(L1) Out[3]: 4436443080

In [4]: id(L2) Out[4]: 4436349576

Example 2: In [5]: a = 10

In [6]: b = 10

In [7]: id(a) Out[7]: 4401921584

In [8]: id(b) Out[8]: 4401921584

Upvotes: 2

Cat Plus Plus
Cat Plus Plus

Reputation: 129754

Because everything is an object, everything has an object bookkeeping overhead. In CPython, it's at least size of a type pointer and reference count for every object. Plus whatever specific objects need for their data. And there's also garbage collector overhead for some objects. Certainly nothing is 'wasted', it's a silly idea.

And there is no char in Python, 'a' is a string of length 1.

Upvotes: 15

Related Questions