Why is “not” faster than “bool()” in Python (or, speed of Python functions vs. statements)?

后端 未结 2 1059
北恋
北恋 2021-01-11 19:41

I made an interesting observation the other day. I was experimenting with various ways to get the \"truthiness\" of an object and the speed of each, and I noticed that

相关标签:
2条回答
  • 2021-01-11 19:59

    All function calls have significant overhead -- you're creating a new stack frame to hold the new locals you have within your call, after all.

    If this were a more expensive operation, that overhead would get lost in the noise. Since you're looking at such a trivial operation, it stands out.

    0 讨论(0)
  • 2021-01-11 20:01

    (This is not supposed to be an answer, just documentation): These are the byte code sequences of the given expressions:

    bool(a):

    1           0 LOAD_NAME                0 (bool)
                3 LOAD_NAME                1 (a)
                6 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
                9 RETURN_VALUE
    

    not a:

    1           0 LOAD_NAME                0 (a)
                3 UNARY_NOT
                4 RETURN_VALUE
    

    not not a:

    1           0 LOAD_NAME                0 (a)
                3 UNARY_NOT
                4 UNARY_NOT
                5 RETURN_VALUE
    
    0 讨论(0)
提交回复
热议问题