From 1ec85e90cd406aa87cb0bc525cdd4690c9730880 Mon Sep 17 00:00:00 2001 From: Edan David Date: Tue, 21 Jun 2016 10:18:28 -0400 Subject: [PATCH] Use {} instead of dict() There is a performance impact when using dict() instead of {} in CPython (up to 6 times longer). Considering the to_primitive function is recursive this can have quite an effect. Measuring: $ python2.7 -m timeit -n 1000000 -r 5 -v 'dict()' raw times: 0.24 0.24 0.24 0.239 0.24 1000000 loops, best of 5: 0.239 usec per loop $ python2.7 -m timeit -n 1000000 -r 5 -v '{}' raw times: 0.0417 0.0413 0.0407 0.0411 0.042 1000000 loops, best of 5: 0.0407 usec per loop For more information: https://doughellmann.com/blog/2012/11/12/ the-performance-impact-of-using-dict-instead-of-in-cpython-2-7-2/ Change-Id: Ia0b5892773a19cbabe40313a3bc788580a943f53 --- oslo_serialization/jsonutils.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/oslo_serialization/jsonutils.py b/oslo_serialization/jsonutils.py index 7bfe944..c4db1b9 100644 --- a/oslo_serialization/jsonutils.py +++ b/oslo_serialization/jsonutils.py @@ -143,8 +143,8 @@ def to_primitive(value, convert_instances=False, convert_datetime=True, level=level, max_depth=max_depth) if isinstance(value, dict): - return dict((recursive(k), recursive(v)) - for k, v in six.iteritems(value)) + return {recursive(k): recursive(v) + for k, v in six.iteritems(value)} elif hasattr(value, 'iteritems'): return recursive(dict(value.iteritems()), level=level + 1) # Python 3 does not have iteritems