-1

This is about the well-known https://fmt.dev/latest/index.html. On the one hand, fmt::format("Mom {} and Dad {}", "Alice", "Bob") is expressive, and on the other hand, fmt::format_to also exists, e.g.

auto out = fmt::memory_buffer();
fmt::format_to(std::back_inserter(out),
          "Mom {} and Dad.", "Alice", "Bob");
auto data = out.data(); // pointer to the formatted data
auto size = out.size(); // size of the formatted data

as adapted from the docs https://fmt.dev/latest/index.html. Now, which one is more efficient? Does the first version -- fmt::format() -- cause unnecessary string concatenations? To my taste, the first version wins hands-down in terms of expressiveness.

Ilonpilaaja
  • 1,169
  • 2
  • 15
  • 26

1 Answers1

3

You can trivially look at the code yourself. fmt::format calls fmt::vformat which calls detail::vformat ... which is equivalent to the code you just wrote, except with a call to the std::string constructor at the end:

namespace detail {
...
template <typename Locale, typename Char>
auto vformat(const Locale& loc, basic_string_view<Char> fmt,
             basic_format_args<buffer_context<type_identity_t<Char>>> args)
    -> std::basic_string<Char> {
  auto buf = basic_memory_buffer<Char>();
  detail::vformat_to(buf, fmt, args, detail::locale_ref(loc));
  return {buf.data(), buf.size()};
}
...
}
Botje
  • 26,269
  • 3
  • 31
  • 41