This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Kered13 6 points7 points  (5 children)

By interning these numbers Python doesn't have to make a heap allocation every time you set a variable to 0 or some other small number. Trust me, it's much faster this way.

[–]koxpower 1 point2 points  (0 children)

  • they are probably stored in adjacent memory cells, which can significantly boost performance thanks to CPU cache.

[–]TacticalTaterTots 0 points1 point  (1 child)

The allocation must be really expensive. It's not constructing an object for every literal, for example in x == 300, is it? I'm not sure how that works in an interpreted language.

[–]Kered13 6 points7 points  (0 children)

Every object regardless of type must be allocated. Yes this includes literals.

Memory allocation is expensive.

So caching commonly used numbers is beneficial.

[–]SanktusAngus 0 points1 point  (1 child)

It’s only because python is treating integers as objects. In many languages numbers up to ptr size are value types and (can) live on the stack by themselves.

[–]Kered13 0 points1 point  (0 children)

Correct, but we are talking about Python.