Skip to content

Instantly share code, notes, and snippets.

@arlukin
Last active July 28, 2016 08:26
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arlukin/10931012 to your computer and use it in GitHub Desktop.
Save arlukin/10931012 to your computer and use it in GitHub Desktop.
Benchmark of merging dicts in python.
#!/usr/bin/env python
import timeit
def d():
d1= {
'title': u'xyx',
'description': u'xyx',
'checkin_time': u'xyx',
'checkout_time': u'xyx',
'active': u'xyx',
'booking_from': u'xyx',
'booking_to': u'xyx',
'publish_from': u'xyx',
'publish_to': u'xyx',
'min_beds': u'xyx',
'max_beds': u'xyx'
};
d2={
'accept_price': u'xyx',
'reservation_price': u'xyx',
'start_price': u'xyx',
'auction_from': u'xyx',
'auction_to': u'xyx'
};
d3={
'day-price': u'xyx',
'days': {
'0': {'from_date': u'xyx', 'to_date': u'xyx'}
},
'checkin_weekday': u'',
'checkout_weekday': u'',
'min_day_stay': u'xyx',
'max_day_stay': u'xyx'
}
return d1, d2, d3
statements = [
'd4 = d1.copy(); d4.update(d2), d4.update(d3)',
'd4 = dict(d1, **d2); d4.update(d3)',
'd4 = {}; d4.update(d1); d4.update(d2), d4.update(d3)',
'd4 = dict(d1, **d2); d5=dict(d4, **d3)',
'd4 = reduce(lambda x,y: dict(x, **y), (d1, d2, d3))',
'd4 = {}\nfor d in (d1, d2, d3): d4.update(d)',
'd4 = dict(d1)\nfor d in (d2, d3): d4.update(d)',
'd4 = dict(chain(*[d.iteritems() for d in (d1, d2, d3)]))',
'd4 = dict(d1.items() + d2.items() + d3.items())',
'd4 = dict(chain.from_iterable(d.iteritems() for d in (d1, d2, d3)))',
'd4 = dict(chain(d1.items(), d2.items(), d3.items()))',
]
if __name__ == '__main__':
res = []
for s in statements:
t = timeit.timeit(
s,
setup="from itertools import chain;from __main__ import d; d1, d2, d3 = d()"
)
st = "time %s --- %s " % (t, s.replace('\n', ' '))
print st
res.append(st)
print "------- In time order -------"
for x in sorted(res):
print x
time 1.6452050209 --- d4 = d1.copy(); d4.update(d2), d4.update(d3)
time 1.69228887558 --- d4 = dict(d1, **d2); d4.update(d3)
time 1.78650903702 --- d4 = {}; d4.update(d1); d4.update(d2), d4.update(d3)
time 1.92449307442 --- d4 = {} for d in (d1, d2, d3): d4.update(d)
time 2.00036215782 --- d4 = dict(d1, **d2); d5=dict(d4, **d3)
time 2.04427695274 --- d4 = dict(d1) for d in (d2, d3): d4.update(d)
time 2.68033099174 --- d4 = reduce(lambda x,y: dict(x, **y), (d1, d2, d3))
time 3.72226691246 --- d4 = dict(chain(*[d.iteritems() for d in (d1, d2, d3)]))
time 4.01872420311 --- d4 = dict(d1.items() + d2.items() + d3.items())
time 4.07779598236 --- d4 = dict(chain.from_iterable(d.iteritems() for d in (d1, d2, d3)))
time 4.23182702065 --- d4 = dict(chain(d1.items(), d2.items(), d3.items()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment