python-betterproto
python-betterproto copied to clipboard
Micro-optimisations
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.getwhen 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__tobetterproto.Messagethis 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)