Skip to content

Instantly share code, notes, and snippets.

@mambocab
Last active August 29, 2015 14:06
Show Gist options
  • Save mambocab/e2a9f2963bbadd972b32 to your computer and use it in GitHub Desktop.
Save mambocab/e2a9f2963bbadd972b32 to your computer and use it in GitHub Desktop.
memoizing object speed demo
class memo():
'''adapted from https://github.com/timm/sbse14/wiki/basepy'''
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def test_memo():
m = memo(stats=memo(mean=3.5, median=3),
author=memo(name='Jim Witschey', twitter='mambocab', github='mambocab'))
m.author.age = 25
def test_dict():
d = { 'stats': { 'mean': 3.5, 'median': 3 },
'author': { 'name': 'Jim Witschey',
'twitter': 'mambocab',
'github': 'mambocab' } }
d['author']['age'] = 25
echo "class: " ; python -mtimeit -s'import speedtest' 'speedtest.test_memo()'
echo "dict: " ; python -mtimeit -s'import speedtest' 'speedtest.test_dict()'
❯ ./speedtest.sh
class:
100000 loops, best of 3: 3.08 usec per loop
dict:
1000000 loops, best of 3: 0.57 usec per loop
❯ ./speedtest.sh
class:
100000 loops, best of 3: 2.98 usec per loop
dict:
1000000 loops, best of 3: 0.562 usec per loop
❯ ./speedtest.sh
class:
100000 loops, best of 3: 3.13 usec per loop
dict:
1000000 loops, best of 3: 0.606 usec per loop
❯ ./speedtest.sh
class:
100000 loops, best of 3: 3.2 usec per loop
dict:
1000000 loops, best of 3: 0.554 usec per loop
@mambocab
Copy link
Author

mambocab commented Sep 9, 2014

So, looks like the class-creation memoization approach is ~5x slower than dictionaries.

@mambocab
Copy link
Author

mambocab commented Sep 9, 2014

I should be more precise: it's slower at memo-creation time. I can't speak to access.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment