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

后端 未结 2 1062
北恋
北恋 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 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
    

提交回复
热议问题