python-betterproto icon indicating copy to clipboard operation
python-betterproto copied to clipboard

Micro-optimisations

Open Gobot1234 opened this issue 3 years ago • 0 comments

In no particular order:

  • Remove abc.ABC as base class for Message - after asking there was no reason for this, saves a bit of Message type creation time
  • Use frozensets for contains checks - as all the TYPE_x strings and integers are interned by the compiler there's no reason to not do this, this makes container checks ~4x faster (200ns vs 50ns) but this is obviously performed a lot of times in BetterProto.
  • Inline functions where possible - this inlines the _pack_fmt call and pre-compiles the struct.Struct instances for each packing string.
  • Don't create a bytearray for each call to _serialize_single - initially when I made this optimisation I don't think I realised there wasn't much point in doing this as it's called so frequently so avoiding the global lookup and call and then taking the hit of concatenating the bytes is fine.
  • Optimise for the normal case for dict.getitem - Calling dict.get when the key is very likely to be there is unneccesary.
  • Get rid of __raw_get - This avoids calling Message.__getattribute__ the call frame and super() initialisation.
  • Added __slots__ to betterproto.Message this reduces size in memory and doesn't change code for the end user (they can still add dynamic attributes)
  • Optimise from_dict slightly better - Reduces the complexity of from_dict, the number of comparisions and dictionary lookups (might also need reverting)

Gobot1234 avatar Apr 11 '22 23:04 Gobot1234