Skip to content

Instantly share code, notes, and snippets.

@davidwtbuxton
Created February 14, 2012 14:27
Show Gist options
  • Save davidwtbuxton/1827083 to your computer and use it in GitHub Desktop.
Save davidwtbuxton/1827083 to your computer and use it in GitHub Desktop.
Comparison of LBYL versus EAFP
# Comparison of LBYL versus EAFP
# http://www.reddit.com/r/Python/comments/pou99/python_performance_tips_part_1/
from __future__ import print_function
from hashlib import md5
_lbyl_cache = {}
_eafp_cache = {}
def calculation(x):
"""Does an 'expensive' calculation with the input."""
return md5(str(x).encode('ascii')).hexdigest()
def lbyl(x):
"""Look before you leap strategy."""
if x not in _lbyl_cache:
_lbyl_cache[x] = calculation(x)
return _lbyl_cache[x]
def eafp(x):
"""Easier to ask forgiveness than permission strategy."""
try:
return _eafp_cache[x]
except KeyError:
_eafp_cache[x] = calculation(x)
return _eafp_cache[x]
def test1(func):
"""Many repeated values, would benefit from memo-ization."""
for x in range(200):
func(x % 5)
flush()
def test2(func):
"""Unique values, defeats memo-ization."""
for x in range(200):
func(x)
flush()
def flush():
global _lbyl_cache
global _eafp_cache
_lbyl_cache = {}
_eafp_cache = {}
if __name__ == "__main__":
import timeit
setup = 'from __main__ import test1, test2, lbyl, eafp'
n = 10000
print('Memo-ization friendly test')
t1 = timeit.repeat('test1(lbyl)', setup, number=n)
t2 = timeit.repeat('test1(eafp)', setup, number=n)
print('LBYL', t1)
print('EAFP', t2)
print('Difference', min(t1) / min(t2))
print('Memo-ization un-friendly test')
t1 = timeit.repeat('test2(lbyl)', setup, number=n)
t2 = timeit.repeat('test2(eafp)', setup, number=n)
print('LBYL', t1)
print('EAFP', t2)
print('Difference', min(t1) / min(t2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment