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?
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 no difference, except for what names from re are visible in you local namespace after the import.
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.