String concatenations benchmarks (updated)

126 points hunua

The widely quoted string concatenation benchmarks by Hendrik Sollich are 4 years old. I added a few methods and some macros from crates.io and re-ran the benches. Here are the results:

0 ns/iter (+/- 0)        from_bytes
10 ns/iter (+/- 0)       concat_string_macro
10 ns/iter (+/- 0)       concat_strs_macro
10 ns/iter (+/- 0)       mut_string_with_capacity_push_str_char
10 ns/iter (+/- 0)       string_concat_macro
10 ns/iter (+/- 1)       mut_string_with_capacity_push_str
14 ns/iter (+/- 0)       concat_in_place_macro
19 ns/iter (+/- 10)      mut_string_with_too_much_capacity_push_str
22 ns/iter (+/- 0)       array_join
24 ns/iter (+/- 0)       array_concat
24 ns/iter (+/- 0)       array_join_long
24 ns/iter (+/- 0)       mut_string_push_str
27 ns/iter (+/- 0)       string_from_plus_op
27 ns/iter (+/- 0)       to_string_plus_op
29 ns/iter (+/- 0)       to_owned_plus_op
30 ns/iter (+/- 0)       collect_from_array_to_string
34 ns/iter (+/- 0)       collect_from_vec_to_string
39 ns/iter (+/- 0)       mut_string_with_too_little_capacity_push_str
43 ns/iter (+/- 1)       string_from_all
52 ns/iter (+/- 0)       format_macro
53 ns/iter (+/- 0)       format_macro_implicit_args
68 ns/iter (+/- 1)       mut_string_push_string

The main takeaways for concatenation are:

  1. format!() is 5 times slower the fastest method
  2. pushing str or char into a mutable string of the right capacity is the fastest method
  3. method [2] can be replaced with one of the macros from crates.io because they implement exactly that

This ReadMe explains what is behind the benches.

New additions to the original study

  1. format!() macro with implicit arguments added in Rust 1.58
let datetime = &format!("{DATE}{T}{TIME}");
  1. several string concatenation macros from crates.io

What did I miss?

Are there other ways or macros to concatenate strings not included in the benches?
I can add them to this draft PR https://github.com/hoodie/concatenation_benchmarks-rs/pull/11.