10

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?

1
  • Premature optimization is evil. Please provide some specific thing to optimize. Blanket "is more efficient" questions are meaningless without a specific piece of code to measure. Commented Dec 7, 2008 at 14:15

3 Answers 3

17

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+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.
16

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.

1 Comment

I think it is also best to study the difference in terms of memory loads to accompany the timing.
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.