Setting local variables to a function instead of using globals optimize the function

左心房为你撑大大i 提交于 2019-12-01 19:32:51

Is there a practical noticeable speed-up (that could balance the inconvenience of the larger function signature)?

I very much doubt it, as the lookups occur once each in the original definition. Note that you've changed the meaning of the function.

In which specific conditions the use of local variables in a case as the one shown would be relevant?

Only inside a tight loop; in this case, if dot_product where used in say a very large matrix multiplication (which you wouldn't do in pure Python anyway, let alone with iterators).

EDIT: I just disassembled both functions and my hunch was wrong, though my point still stands:

>>> def dotproduct(vec1, vec2):
...     return sum(imap(operator.mul, vec1, vec2))
...
>>> dis.dis(dotproduct)
  2           0 LOAD_GLOBAL              0 (sum)
              3 LOAD_GLOBAL              1 (imap)
              6 LOAD_GLOBAL              2 (operator)
              9 LOAD_ATTR                3 (mul)
             12 LOAD_FAST                0 (vec1)
             15 LOAD_FAST                1 (vec2)
             18 CALL_FUNCTION            3
             21 CALL_FUNCTION            1
             24 RETURN_VALUE
>>> def dotproduct(vec1, vec2, sum=sum, imap=imap, mul=operator.mul):
...     return sum(imap(mul, vec1, vec2))
...
>>> dis.dis(dotproduct)
  2           0 LOAD_FAST                2 (sum)
              3 LOAD_FAST                3 (imap)
              6 LOAD_FAST                4 (mul)
              9 LOAD_FAST                0 (vec1)
             12 LOAD_FAST                1 (vec2)
             15 CALL_FUNCTION            3
             18 CALL_FUNCTION            1
             21 RETURN_VALUE
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!