efficiency question

D

David Harvey

Hi,

Suppose I write

if x in ("abc", "def", "xyz"):
doStuff()

elif x in ("pqr", "tuv", "123"):
doOtherStuff()

elif ...

etc.

When is python building the tuples? Does it need to build the tuple
every time it comes through this code? Or does it somehow recognise
that they are constant and cache them?

In other words, is anything gained (efficiency-wise) by first putting
say

tuple1 = ("abc", "def", "xyz")
tuple2 = ("pqr", "tuv", "123")

somewhere where I know it's executed once, and then writing

if x in tuple1:
doStuff()

elif x in tuple2:
doOtherStuff()

elif ...

????

(The tuples I have in mind are of course much longer than three
elements)

Many thanks

David
 
S

Scott David Daniels

David said:
if x in ("abc", "def", "xyz"):
doStuff()
elif x in ("pqr", "tuv", "123"):
doOtherStuff()
elif ...

If the code really looks like this:
# one-time-only code
big_dispatch_table = {}
for function, keys in [
(doStuff, ["abc", "def", "xyz"]),
(doOtherStuff, ["pqr", "tuv", "123"]),
... ]:
for key in keys:
big_dispatch_table[key] = function


Then your actual code goes something like:

big_dispatch_table[x]()

--Scott David Daniels
(e-mail address removed)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top