Is it more efficient to use "import <module>" or "from <module> import <func>"?
Let's say I needed to use findall () from the re module, is it more efficient to do this:
from re import findall
or
import re
Is there any difference in speed / memory usage etc.
There is no difference in imports, however there is a slight difference in access.
When you access a function like
re.findall()
python must first find the module in the global scope and then findall in the dict modules. It can matter if you call it thousands of times inside the loop.
When in doubt, time:
from timeit import Timer
print Timer("""re.findall(r"\d+", "fg12f 1414 21af 144")""", "import re").timeit()
print Timer("""findall(r"\d+", "fg12f 1414 21af 144")""", "from re import findall").timeit()
I get the following results using a minimum of 5 repetitions out of 10,000,000 calls:
re.findall(): 123.444600105
findall(): 122.056155205
It looks like using it findall()
directly, rather than re.findall()
having a very minor advantage of using it.
However, the actual import operators differ in their speed by a significant amount. On my computer, I get the following results:
>>> Timer("import re").timeit()
2.39156508446
>>> Timer("from re import findall").timeit()
4.41387701035
So, import re
it turns out to be about twice as fast as execution. Presumably, however, executing the imported code is your bottleneck and not the actual import.
There is no difference other than which names from re are visible in your local namespace after import.