Created
February 4, 2015 20:26
-
-
Save radix/a3d3234122e1e553f431 to your computer and use it in GitHub Desktop.
Pyrsistent PRecord vs POPO copy+mutate
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
| from __future__ import print_function | |
| import copy | |
| from pyrsistent import PRecord, field | |
| NUM_FIELDS = 20 | |
| def make_pfoo(attr_names): | |
| field_decls = [' %s = field()' % (attr,) for attr in attr_names] | |
| stmt = """ | |
| class PFoo(PRecord): | |
| """ + '\n'.join(field_decls) | |
| print(stmt) | |
| return stmt | |
| def make_sfoo(attr_names): | |
| assignments = [' self.{arg} = {arg}'.format(arg=arg) | |
| for arg in attr_names] | |
| stmt = """ | |
| class SFoo(object): | |
| def __init__(self, {args}): | |
| {assignments} | |
| """.format(args=', '.join(attr_names), | |
| assignments='\n'.join(assignments)) | |
| print(stmt) | |
| return stmt | |
| def make_attr_names(num_attrs): | |
| return ['field%s' % (x,) for x in xrange(num_attrs)] | |
| attrs = make_attr_names(NUM_FIELDS) | |
| exec make_pfoo(attrs) | |
| exec make_sfoo(attrs) | |
| def obj_assoc(obj, **changes): | |
| new_obj = copy.copy(obj) | |
| new_obj.__dict__.update(changes) | |
| return new_obj | |
| def standard_obj_updates(): | |
| obj = SFoo(*attrs) | |
| for x in xrange(1000): | |
| for attr in attrs: | |
| new_obj = obj_assoc(obj, **{attr: 'newval'}) | |
| def pyrsistent_obj_updates(): | |
| kwargs = {name: name for name in attrs} | |
| obj = PFoo(**kwargs) | |
| for x in xrange(1000): | |
| for attr in attrs: | |
| new_obj = obj.set(**{attr: 'newval'}) | |
| import timeit | |
| print("standard obj_assoc:", timeit.repeat(standard_obj_updates, number=10)) | |
| print("PRecord .set: ", timeit.repeat(pyrsistent_obj_updates, number=10)) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results on my laptop:
CPython, 5 fields:
PyPy, 5 fields:
CPython, 10 fields:
PyPy, 10 fields:
CPython, 20 fields:
PyPy, 20 fields: