https://gcc.gnu.org/bugzilla/show_bug.cgi?id=112925
Bug ID: 112925 Summary: Optimize std::string construction from std::istreambuf_iterator Product: gcc Version: 14.0 Status: UNCONFIRMED Keywords: missed-optimization Severity: normal Priority: P3 Component: libstdc++ Assignee: unassigned at gcc dot gnu.org Reporter: redi at gcc dot gnu.org Target Milestone: --- Something like this would improve performance considerably. Instead of reading a character at a time we can use streambuf::sgetn to copy directly into the string's unused capacity: --- a/libstdc++-v3/include/bits/basic_string.tcc +++ b/libstdc++-v3/include/bits/basic_string.tcc @@ -205,6 +205,21 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION _M_data(__another); _M_capacity(__capacity); } + +#if __cplusplus >= 201103L && 0 + using _BufIter = istreambuf_iterator<_CharT, char_traits<_CharT>>; + if _GLIBCXX17_CONSTEXPR (is_same<_InIterator, _BufIter>::value) + { + if (!std::__is_constant_evaluated()) + { + auto __r = std::__copy_n_a(__beg, capacity() - size(), + data() + size(), false); + __len = __r - data(); + _M_set_length(__len); + continue; + } + } +#endif traits_type::assign(_M_data()[__len++], *__beg); ++__beg; }