Last active
August 1, 2019 06:56
-
-
Save yuwash/699be7962f280fad2212317d2cdd3766 to your computer and use it in GitHub Desktop.
Performance test example [EAFP vs. LBYL](https://david.goodger.org/projects/pycon/2007/idiomatic/handout.html#id48)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env python | |
# -*- coding: utf-8 -*- | |
expect_at = 2**22 | |
plants = expect_at * ['wind'] + ['solar'] + expect_at * ['biogas'] | |
repetitions = 100 | |
def where_is_eafp(target): | |
try: | |
return plants.index(target) | |
except ValueError: | |
return -1 | |
def where_is_lbyl(target): | |
if target in plants: | |
return plants.index(target) | |
else: | |
return -1 | |
def where_is_direct(target): | |
for i, plant in enumerate(plants): | |
if plant == target: | |
return i | |
return -1 | |
if __name__ == '__main__': | |
where_is = dict( | |
lbyl=where_is_lbyl, | |
eafp=where_is_eafp, | |
direct=where_is_direct, | |
)['eafp'] | |
for i in range(repetitions): | |
there = where_is('solar') | |
print(there) | |
for i in range(repetitions): | |
where_is('coal') # doesn’t exist |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In my test with
expect_at=2**22, repetitions=100
on a dualcore 1.10 GHz laptop the benchmark result wasEAFP
LBYL
direct
By using a larger list than below, this time the result shows a clear superiority of the EAFP implementation as expected.
Unsuccessful search only
When limited to only unsuccessful searches (“coal”), I expected LBYL to be slightly superior as it only does “target in plants” and not “plants.index”, but I was wrong. EAFP was still slightly better (other parameters as above):
EAFP
LBYL
direct
Previous attempt
This first attempt was done with
expect_at=100, repetitions=2**22
. This was not a very optimal choice so that the result only shows marginal differences.In my test on a quadcore 2.5 GHz laptop the benchmark result was
EAFP
LBYL
direct
Thus the difference between EAFP and LBYL is minimal, but on repetitive tests EAFP was consistently (slightly) faster. The horrible performance of the “direct” approach is yet another confirmation that you should use library functions (probably implemented in C) instead of writing loops in Python.