fmtlib / fmt

A modern formatting library
https://fmt.dev
Other
20.74k stars 2.49k forks source link

println implementation allocates an std::string #3301

Closed ilyapopov closed 1 year ago

ilyapopov commented 1 year ago

Currently, println is implemented using fmt::format:

https://github.com/fmtlib/fmt/blob/581c6292c98f998622f6adf0e6f0f5cb47704269/include/fmt/core.h#L3018

This creates an intermediate std::string that is being allocated and deallocated. It would be nice if println could avoid that.

ilyapopov commented 1 year ago

I see that the implementation is word-for-word from the standard: https://eel.is/c++draft/iostream.format#ostream.formatted.print-2

However, the standard does not mandate this exact implementation, is says "equivalent to".

vitaut commented 1 year ago

Thanks for the suggestion but I don't think it's worth investing time in trying to optimize println because it's mostly there for (minor) convenience, not performance. In the unlikely case println is a perf bottleneck in your program you are better off using a different API like output_file (https://www.zverovich.net/2020/08/04/optimal-file-buffer-size.html) altogether.

ilyapopov commented 1 year ago

I agree that this alone is not a critical issue. However, if such inefficiencies are allowed to accumulate in time, for such widely used and foundational library as fmt this may become an issue in the future.