Python Language Garbage Collection Reuse of primitive objects

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!


An interesting thing to note which may help optimize your applications is that primitives are actually also refcounted under the hood. Let's take a look at numbers; for all integers between -5 and 256, Python always reuses the same object:

>>> import sys
>>> sys.getrefcount(1)
>>> a = 1
>>> b = 1
>>> sys.getrefcount(1)

Note that the refcount increases, meaning that a and b reference the same underlying object when they refer to the 1 primitive. However, for larger numbers, Python actually doesn't reuse the underlying object:

>>> a = 999999999
>>> sys.getrefcount(999999999)
>>> b = 999999999
>>> sys.getrefcount(999999999)

Because the refcount for 999999999 does not change when assigning it to a and b we can infer that they refer to two different underlying objects, even though they both are assigned the same primitive.

Got any Python Language Question?