0

In my understanding, all things in python are object and some of them per-allocate memory to them (for int the range is from -5 to 256).
My question is if the address not per-allocate, does it create in fly?

for example:

print id(256)
a = 256
print id(a)

36609008
36609008

this example indicates variable a is referring the object 256's memory, thus they have same address.

print id(300)
a = 300
print id(a)

106711544
106708304

for the example above:

  1. does python create two objects? (it seems yes)
  2. why -5 to 256?
  3. would those per-allocated object be reused to create new objects?
galaxyan
  • 5,944
  • 2
  • 19
  • 43
  • For the CPython implementation at least, yes it does. – tdelaney Apr 20 '18 at 21:23
  • As you can see from the object `id`s, yes, python has created two objects. – Prune Apr 20 '18 at 21:24
  • @tdelaney so further question is why -5 to 256? – galaxyan Apr 20 '18 at 21:24
  • 2
    The small integers are preallocated for speed. Other integer objects are allocated in blocks and may be reassigned different values as ref counts go to zero (meaning it has no user and can be recycled for a new integer). – tdelaney Apr 20 '18 at 21:25
  • 1
    In the C implementation, all objects share a common header. Integers can't be different because then they would need to be special-cased throughout any C Extensions that use them. – tdelaney Apr 20 '18 at 21:27
  • @tdelaney I agree. For the speed part, why -5 to 256? based on what? – galaxyan Apr 20 '18 at 21:28
  • Based on a wild guess, mostly. I don't have the details of the implementation but I bet it has something to do with the size of the blocks allocated. – tdelaney Apr 20 '18 at 21:29
  • @tdelaney haha, that is the part I could not figure out. I think the block size is from 5 to 512b. – galaxyan Apr 20 '18 at 21:33

0 Answers0