The Importance of Not Over-Optimizing in Rust

Story time!

Meet Gene!

  • Python Developer
  • Aggregating JSON
  • Heard Rust is faster than Python

            #[derive(Deserialize)]
            struct Data {
                name: String,
                value: u16,
            }
          

            #[derive(Deserialize)]
            struct Data<'a> {
                name: &'a str,
                value: u16,
            }
         

            #[derive(Deserialize)]
            struct Data<'a> {
                name: &'a str,
                value: u16,
            }
          
  • Lifetimes
  • Generic arguments
  • References
  • Ownership
Without Lifetimes

          fn parse_json(input: &str) -> Data {
              serde_json::from_str(input).unwrap()
          }
          
With Lifetimes

          fn parse_json<'a>(input: &'a str) -> Data<'a> {
              serde_json::from_str(input).unwrap()
          }
          
Without Lifetimes

          impl Data {
            ...
          }
          
With Lifetimes

          impl<'a> Data<'a> {
            ...
          }
          
Without Lifetimes

          struct DataCollection {
              data_values: Vec<Data>,
          }
          
With Lifetimes

          struct DataCollection<'a> {
              data_values: Vec<Data<'a>>,
          }
          

😃

😕

Did Gene have to learn these things right away?

Start with this

            fn remove_trailing_spaces(s: String) -> String {
                s.trim_end().to_string()
            }
          
Write this when you have to

            fn remove_trailing_spaces(s: &str) -> &str {
                s.trim_end()
            }
          

How does Rust Look to New Developers?

Naïve Rust is often "fast enough"

  • Become productive faster
  • Write code that's faster but not fastest
  • Reduce developers leaving community
  • Topics are not going anywhere

New Developers

  • Use Owned values
  • Use .clone()
  • Use Rc/Arc
  • Compile with --release!

Thank you!

manning.com/books/refactoring-to-rust