On 21.07.2012 12:06, Steven D'Aprano wrote:

But in general, you're worrying too much about trivia. One way or the
other, any speed difference will be trivial. Write whatever style reads
and writes most naturally, and only worry about what's faster where it
actually counts.



Notice that I try to make each function do the same amount of work, so
that we're seeing only the difference between "else" vs "no else".

Now let's test the speed difference with Python 2.7. Because this is
timing small code snippets, we should use the timeit module to time the
code:

from timeit import Timer
setup = "from __main__ import with_else, without_else"
t1 = Timer("for i in (0, 1): result = with_else(i)", setup)
t2 = Timer("for i in (0, 1): result = without_else(i)", setup)

Each snippet calls the function twice, once to take the if branch, then
to take the else branch.

Now we time how long it takes to run each code snippet 1000000 times. We
do that six times each, and print the best (lowest) speed:

py> min(t1.repeat(repeat=6))
0.9761919975280762
py> min(t2.repeat(repeat=6))
0.9494419097900391

So there is approximately 0.03 second difference per TWO MILLION
if...else blocks, or about 15 nanoseconds each. This is highly unlikely
to be the bottleneck in your code. Assuming the difference is real, and
not just measurement error, the difference is insignificant.

So, don't worry about which is faster. Write whichever is more natural,
easier to read and write.



Hello Steven,

very nice example and thank you very much for also for the Timeit test!
Actually it confirms my assumption in some way:

[SNIP myself]
So if there is some overhead in some fashion in case we don't offer the
else, assuming the interpreter has to exit the evaluation of the
"if"-statement clause and return to a "normal parsing code"-state
outside the if statement itself.
[SNAP]

Without having looked at Andrew's bytecode excecution hint, using the dis module, to see how the interpreter handles the task on lower level.

But fare enough for me :)

But I agree, the return in my example is misleading and it would be illegal outside of a function call. I just added it to make clear that the fellow code below the return should not be executed in comparison to the 2nd example.

Thank you very much
Jan
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to