Say I only needed to use findall() from the re module, is it more efficient to do:
from re import findall
or
import re
Is there actually any difference in speed/memory usage etc?
There is a difference, because in the import x version there are two name lookups: one for the module name, and the second for the function name; on the other hand, using from x import y , you have only one lookup. As you can see, using the form from x import y is a bit faster.
The 4 ways to import a module Import specific things from the module: pycon from random import choice, randint. Import the whole module and rename it, usually using a shorter variable name: pycon import pandas as pd. Import specific things from the module and rename them as you're importing them: pycon from os.
The difference between import and from import in Python is: import imports the whole library. from import imports a specific member or members of the library.
There is no difference on the import, however there is a small difference on access.
When you access the function as
re.findall()
python will need to first find the module in the global scope and then find findall in modules dict. May make a difference if you are calling it inside a loop thousands of times.
When in doubt, time it:
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 the minimum of 5 repetitions of 10,000,000 calls:
re.findall(): 123.444600105
findall(): 122.056155205
There appears to be a very slight usage advantage to using findall()
directly, rather than re.findall()
.
However, the actual import statements 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
appears to be approximately twice as fast to execute. Presumably, though, execution of the imported code is your bottleneck, rather than the actual import.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With