Why mesh python code slower than decomposed one?

后端 未结 1 831
一整个雨季
一整个雨季 2021-02-20 03:29

I\'ve discovered surprising python behaviour while had investigating thread Why is reading lines from stdin much slower in C++ than Python?.

If I run simple python code

相关标签:
1条回答
  • 2021-02-20 04:03

    Watching into bytecode helped me to answer this question. Byte code for working part of the first script is:

     10          58 SETUP_LOOP              27 (to 88)
                 61 LOAD_NAME                3 (sys)
                 64 LOAD_ATTR                6 (stdin)
                 67 GET_ITER         
            >>   68 FOR_ITER                16 (to 87)
                 71 STORE_NAME               7 (line)
     11          74 LOAD_NAME                4 (count)
                 77 LOAD_CONST               4 (1)
                 80 INPLACE_ADD      
                 81 STORE_NAME               4 (count)
                 84 JUMP_ABSOLUTE           68
            >>   87 POP_BLOCK
    

    And byte code for corresponding part of second script is:

     12          18 SETUP_LOOP              24 (to 45)
                 21 LOAD_FAST                0 (input)
                 24 GET_ITER
            >>   25 FOR_ITER                16 (to 44)
                 28 STORE_FAST               3 (line)
     13          31 LOAD_FAST                1 (count)
                 34 LOAD_CONST               2 (1)
                 37 INPLACE_ADD
                 38 STORE_FAST               1 (count)
                 41 JUMP_ABSOLUTE           25
            >>   44 POP_BLOCK
    

    I see that actual difference between this codes is LOAD_NAME vs LOAD_FAST and STORE_NAME vs STORE_FAST opcodes using. Documentation http://docs.python.org/2.7/library/dis.html#opcode-LOAD_FAST says that LOAD_FAST makes lookup using only indexes, while LOAD_NAME lookups variable by string name. And the first approach is two times faster.

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