Avoid malloc in Serde

Viewed 142

I want to parse json as fast as possible using serde. To do this I want to completely avoid allocating objects on heap on a critical path. I use deserialize_in_place method, which does exactly what I need. I have a PriceLevel struct which has some Vecs inside it. This struct is allocated once and forever. When I parse jsons I reuse the same struct over and over again.

// holder is allocated once and forever
let mut holder = PriceLevel::zero();
// new deserializer is created for each new message
let mut deserializer = Deserializer::from_str(data);
Deserialize::deserialize_in_place(&mut deserializer, &mut holder).unwrap();

This approach allows to remove allocation of the struct itself and its internal Vecs, which is good. However, Deserializer::from_str constructor creates Vec inside it, and I have to create new instance of deserializer for each incoming json message. My question is how to avoid these internal allocations of the deserializer? One solution would be to have a init or reset method in deserializer, which would clear the internal state of the deserializer and allow it to parse another message. Or maybe there is a similar object which allows such reusing?

0 Answers
Related