Last active
August 29, 2015 14:06
-
-
Save mambocab/e2a9f2963bbadd972b32 to your computer and use it in GitHub Desktop.
memoizing object speed demo
This file contains 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
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 |
This file contains 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
echo "class: " ; python -mtimeit -s'import speedtest' 'speedtest.test_memo()' | |
echo "dict: " ; python -mtimeit -s'import speedtest' 'speedtest.test_dict()' |
This file contains 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
❯ ./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 |
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
So, looks like the class-creation memoization approach is ~5x slower than dictionaries.