I have spent quite a bit of time writing Rust code, and also optimizing that same Rust code. In fact I have doubtless spent more time optimizing code than the time saved by the optimizations. In any case, I have some favorite optimizations.
The programs I use tend to copy data (byte vectors) from one source to another. They process data byte-by-byte. But the optimization is to append ranges of bytes, with extend_from_slice
, instead of using push to append each byte individually.
This has some advantages:
extend_from_slice
saves a capacity and length call on each individual byte, and does these checks just once for the entire slice.extend_from_slice
can avoid multiple allocations because it only needs to check the capacity once.You can find more about this Rust optimization in the Rust category on this site—look for the Vec extend_from_slice
article.