Rust Generics Vs Trait Objects: Performance Impact
Rust's generics & trait objects: Generics handle one type, while trait objects can handle multiple types. Generics have no runtime cost, but trait objects incur a dynamic dispatch penalty.
Introduction Abstracting concepts to avoid code duplication is something common. Rust provides both generics and trait objects to achieve this, but if you look carefully they don't address the exact same problem, and they have different consequences on performance. In order to compare them, we will consider a simple example : a list. Let's start with generics. Generics struct MyList<T> { contents: Vec<T>, } fn main() { let a = MyList { contents: vec![1., 2., 3.], }; let b = MyList { contents: vec!["abc".to_owned(), "def".to_owned()], }; printl...