slight performance optimization for ui.show_model_changes
I didn't actually benchmark this, but creating new FormattedItemMapping
views in each iteration of the loop appeared like a rather inefficient
way of doing things. In reality, this is probably completely irrelevant,
since one would usually not show huge numbers of changed Models at a
time.
@@ -666,10 +666,10 @@ def term_width():
FLOAT_EPSILON = 0.01
-def _field_diff(field, old, new):
- """Given two Model objects, format their values for `field` and
- highlight changes among them. Return a human-readable string. If the
- value has not changed, return None instead.
+def _field_diff(field, old, old_fmt, new, new_fmt):
+ """Given two Model objects and their formatted views, format their values
+ for `field` and highlight changes among them. Return a human-readable
+ string. If the value has not changed, return None instead.
"""
oldval = old.get(field)
newval = new.get(field)
@@ -682,8 +682,8 @@ def _field_diff(field, old, new):
return None
# Get formatted values for output.
- oldstr = old.formatted().get(field, u'')
- newstr = new.formatted().get(field, u'')
+ oldstr = old_fmt.get(field, u'')
+ newstr = new_fmt.get(field, u'')
# For strings, highlight changes. For others, colorize the whole
# thing.
@@ -708,6 +708,11 @@ def show_model_changes(new, old=None, fields=None, always=False):
"""
old = old or new._db._get(type(new), new.id)
+ # Keep the formatted views around instead of re-creating them in each
+ # iteration step
+ old_fmt = old.formatted()
+ new_fmt = new.formatted()
+
# Build up lines showing changed fields.
changes = []
for field in old:
@@ -716,7 +721,7 @@ def show_model_changes(new, old=None, fields=None, always=False):
continue
# Detect and show difference for this field.
- line = _field_diff(field, old, new)
+ line = _field_diff(field, old, old_fmt, new, new_fmt)
if line:
changes.append(u' {0}: {1}'.format(field, line))
@@ -727,7 +732,7 @@ def show_model_changes(new, old=None, fields=None, always=False):
changes.append(u' {0}: {1}'.format(
field,
- colorize('text_highlight', new.formatted()[field])
+ colorize('text_highlight', new_fmt[field])
))
# Print changes.
