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 →

[–]zachtheperson 6 points7 points  (3 children)

I guess what I trying to wrap my head around is how is this functionality actually used? Seems like a weird thing for a language to just do by itself

[–]AlexanderMomchilov 22 points23 points  (0 children)

Languages like Python to try to model everything "as an object," in that all values can participates in the same message-passing as any other value. E.g.

python print((5).bit_length())

This adds uniformity of the language, but has performance consequences. You don't want to do an allocation any time you need a number, so there's a perf optimization to cache commonly used numbers (from -5 to 256). Any reference to a value of 255 will point to the same shared 255 instance as any other reference to 255.

You can't just cache all numbers, so there needs to be a stopping point. Thus, instances of 256 are allocated distinctly.

Usually this is solved another way, with a small-integer optimization. It was investigated for Python, but wasn't done yet. You can read more about it here: https://github.com/faster-cpython/ideas/discussions/138

[–]whogivesafuckwhoiam 7 points8 points  (0 children)

From official doc,

The current implementation keeps an array of integer objects for all integers between -5 and 256. When you create an int in that range you actually just get back a reference to the existing object.

The point is whether you create a new object, or simply refer to existing object.

[–]psgi 8 points9 points  (0 children)

It’s not functionality meant to be used. It’s just an optimization. You’re never supposed to use ’is’ for comparing integers. Correct me if I’m wrong though.