1

I read somewhere around that python, for optimization target, makes some caches of small integers and strings, so I made some experimentations.

From test1.py:

x = 150
n = int(input('number: '))
print(id(x))
print(id(n))

So I launched it:

*****@***** ~/Desktop $ python3 test1.py 
number: 150
10459808
10459808

From test2.py:

x = 'hi'
s = (input('write: ')).strip()
print(id(x))
print(id(s))

then:

*****@***** ~/Desktop $ python3 test2.py 
write: hi
140124156034832
140124155359336

Why are integers optimized at run-time and strings not?

Infact if I have:

x = 'hi'
s = 'hi'
print(id(x))
print(id(s))

it returns same ids. So why are strings optimized only at compile-time?

zer0uno
  • 7,521
  • 13
  • 57
  • 86
  • 1
    Completely different caching strategies. All small integers are cached, but only certain string literals used in code and identifiers are interned. The answer on the dupe explains the rules for when a string is interned. – Martijn Pieters Jul 07 '14 at 18:22
  • 1
    For integers: [Python "is" operator behaves unexpectedly with integers](http://stackoverflow.com/q/306313) – Martijn Pieters Jul 07 '14 at 18:23
  • 1
    Also related: [Why (0-6) is -6 = False?](http://stackoverflow.com/questions/11476190/why-0-6-is-6-false) – Ashwini Chaudhary Jul 07 '14 at 18:25
  • 1
    As to why: The set of small integers between -5 and 256 is a *finite set*. We know exactly how many elements need to be cached, so that's easy and manageable. For strings, there is no such small set. – Martijn Pieters Jul 07 '14 at 18:25
  • 1
    Strings are cached to speed up name lookups, mostly. An interned string can use pointer comparisons, faster than character by character value comparisons. As Python uses dictionaries almost exclusively for name lookups, that's a good thing to have. For user input, not so much. – Martijn Pieters Jul 07 '14 at 18:26

0 Answers0