Why does sys.getrefcount give huge values?

前端 未结 2 1352
天涯浪人
天涯浪人 2021-01-21 06:20
import sys

a = 10
b = a
print sys.getrefcount(a)
b=1
print sys.getrefcount(b)

output:

22 614

Is there any problem with my

相关标签:
2条回答
  • 2021-01-21 06:33

    You can see the effects of Python's optimizations (see @Nether's answer) if you change the values to non-trivial ones. For instance, if your code is changed to:

    from __future__ import print_function
    
    import sys
    
    a = 1012345
    b = a
    print(sys.getrefcount(a))
    b=12345678
    print(sys.getrefcount(b))
    

    The output is:

    5
    4
    
    0 讨论(0)
  • 2021-01-21 06:50

    This is because CPython internally keeps an already created integer object with value 1 and internal variables point to it. It makes sense to have only one such object since it is immutable.

    The same thing applies to string literals, since they're immutable compilers generally keep a single unique string in memory and make variables point to it.

    The more unique the literal, the less chance there is for it to be created internally.

    >>> sys.getrefcount(1337)
    3
    >>> sys.getrefcount('p')
    14
    >>> sys.getrefcount('StackOverflow')
    3
    

    As you can see in the internals here, some small integer objects are created and cached for some small optimization. https://github.com/python/cpython/blob/2.7/Objects/intobject.c#L74

    0 讨论(0)
提交回复
热议问题