tags:

views:

292

answers:

3

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?

+3  A: 

There is no difference, except for what names from re are visible in you local namespace after the import.

hop
+7  A: 

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.

Kozyarchuk
+1, but also note that Python will search local namespace before global namespaces, so creating a local function (findall = re.findall) that references the function is the best, and works identically with both import styles.
Tom
+6  A: 

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.

Noah
When are you _ever_ going to import something 1 million times???
hop
I think that's what I was trying to say....
Noah