get_by_key: short-circuit

This is about 30% faster, presumably because it avoids allocation and/or
closing over variables is slow(?). It's not hugely significant (I
misread a line_profile report) but why not.
This commit is contained in:
Will Thompson 2016-03-07 18:52:56 +00:00
parent 7ac68697d4
commit 284caf03c3

View file

@ -75,8 +75,11 @@ def get_positions(ids, pos):
return positions return positions
def get_by_key(objects, key, value): def get_by_key(objects, key, value):
obj = filter(lambda o: o.get(key) == value, objects) for o in objects:
return obj and obj[0] or None if o.get(key) == value:
return o
return None
def get_by_id(objects, id): def get_by_id(objects, id):
return get_by_key(objects, 'id', id) return get_by_key(objects, 'id', id)