If there is a library from which I\'m going to use at least two methods, is there any difference in performance or memory usage between the following?
from X
It can matter if you are calling a function a lot of times in a loop (millions or more). Doing the double dictionary lookup will eventually accumulate. The example below shows a 20% increase.
Times quoted are for Python 3.4 on a Win7 64 bit machine. (Change the range command to xrange for Python 2.7).
This example is highly based on the book High Performance Python, although their third example of local function lookups being better no longer seemed to hold for me.
import math
from math import sin
def tight_loop_slow(iterations):
"""
>>> %timeit tight_loop_slow(10000000)
1 loops, best of 3: 3.2 s per loop
"""
result = 0
for i in range(iterations):
# this call to sin requires two dictionary lookups
result += math.sin(i)
def tight_loop_fast(iterations):
"""
>>> %timeit tight_loop_fast(10000000)
1 loops, best of 3: 2.56 s per loop
"""
result = 0
for i in range(iterations):
# this call to sin only requires only one lookup
result += sin(i)