If/then style question
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Sat Dec 18 19:05:22 EST 2010
On Sat, 18 Dec 2010 12:29:31 +0100, Francesco wrote:
[...]
> I agree to your point, but I'm afraid you chose a wrong example (AFAIK,
> and that's not much). Sure, the second version of function(arg) is much
> more readable, but why do you think the first one would do "*lots* of
> unnecessary work"?
> All the overhead in that function would be:
> if some_condition, three IF tests, and you know that's NOT a lot!
Well, let's try it with a working (albeit contrived) example. This is
just an example -- obviously I wouldn't write the function like this in
real life, I'd use a while loop, but to illustrate the issue it will do.
def func1(n):
result = -1
done = False
n = (n+1)//2
if n%2 == 1:
result = n
done = True
if not done:
n = (n+1)//2
if n%2 == 1:
result = n
done = True
if not done:
n = (n+1)//2
if n%2 == 1:
result = n
done = True
if not done:
for i in range(1000000):
if not done:
n = (n+1)//2
if n%2 == 1:
result = n
done = True
return result
def func2(n):
n = (n+1)//2
if n%2 == 1:
return n
n = (n+1)//2
if n%2 == 1:
return n
n = (n+1)//2
if n%2 == 1:
return n
for i in range(1000000):
n = (n+1)//2
if n%2 == 1:
return n
return -1
Not only is the second far more readable that the first, but it's also
significantly faster:
>>> from timeit import Timer
>>> t1 = Timer('for i in range(20): x = func1(i)',
... 'from __main__ import func1')
>>> t2 = Timer('for i in range(20): x = func2(i)',
... 'from __main__ import func2')
>>> min(t1.repeat(number=10, repeat=5))
7.3219029903411865
>>> min(t2.repeat(number=10, repeat=5))
4.530779838562012
The first function does approximately 60% more work than the first, all
of it unnecessary overhead.
--
Steven
More information about the Python-list
mailing list