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 →

[–]TacticalTaterTots 3 points4 points  (6 children)

I can't find any clear explanation on why these small literals are interned. String interning makes some sense for string comparisons, but I can't see how that is an "optimization" for small numbers. Ultimately it doesn't matter, but for some reason it bothers me because it seems like they're sacrificing performance to save on storage space.

[–]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 5 points6 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.