问题
In the documentation for the itertools module I found this comment
def dotproduct(vec1, vec2):
return sum(imap(operator.mul, vec1, vec2))
Note, many of the above recipes can be optimized by replacing global lookups with local variables defined as default values. For example, the dotproduct recipe can be written as:
def dotproduct(vec1, vec2, sum=sum, imap=imap, mul=operator.mul):
return sum(imap(mul, vec1, vec2))
How is it?.
Is there a practical noticeable speed-up (that could balance the inconvenience of the larger function signature)?
In which specific conditions the use of local variables in a case as the one shown would be relevant?.
Edit: I tested with timeit and there is any relevant difference.
For two 40-items lists as vec1, vec2:
global lookup -> 3.22720959404
local lookup -> 3.19884065683
that is, only ca. 1% gain.
回答1:
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
来源:https://stackoverflow.com/questions/6725223/setting-local-variables-to-a-function-instead-of-using-globals-optimize-the-func