[Tutor] If statement optimization
bodsda at googlemail.com
bodsda at googlemail.com
Fri Sep 16 13:17:17 CEST 2011
Thanks for the explanation - very clear.
Cheers,
Bodsda
Sent from my BlackBerry® wireless device
-----Original Message-----
From: Steven D'Aprano <steve at pearwood.info>
Sender: tutor-bounces+bodsda=googlemail.com at python.org
Date: Fri, 16 Sep 2011 20:43:45
To: Tutor - python List<tutor at python.org>
Subject: Re: [Tutor] If statement optimization
bodsda at googlemail.com wrote:
> Hi,
>
> In a normal if,elif,elif,...,else statement, are the conditions checked in a linear fashion?
Yes.
> I am wondering if I should be making an effort to put the most likely true condition at the beginning of the block
Probably not. The amount of time used in the average if...elif is
unlikely to be significant itself. Don't waste your time trying to
optimize something like this:
if n < 0:
...
elif n == 0:
...
else:
...
However, there are exceptions.
If the tests are very expensive, then it might be worthwhile putting the
most likely case first. Or at least, put the cheapest cases first, leave
the expensive ones for last:
if sum(mylist[1:]) > 1000 and mylist.count(42) == 3 and min(mylist) < 0:
...
elif len(mylist) < 5:
...
I probably should swap the order there, get the cheap len() test out of
the way, and only perform the expensive test if that fails.
If you have LOTS of elif cases, like *dozens*, then firstly you should
think very hard about re-writing your code, because that's pretty poor
design... but if you can't change the design, then maybe it is
worthwhile to rearrange the cases.
If you have something like this:
if s == "spam":
func_spam(x)
elif s == "ham":
func_ham(x)
elif s == "cheese":
func_cheese(x)
you can often turn this into a dispatch table:
table = {"spam": func_spam, "ham": func_ham, "cheese": func_cheese}
func = table[s] # lookup in the dispatch table
func(x) # finally call the function
Note that inside table, you don't call the functions.
This pattern is especially useful, as lookup in a table in this manner
takes close enough to constant time, whether there is one item or a million.
--
Steven
_______________________________________________
Tutor maillist - Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list