https://gcc.gnu.org/bugzilla/show_bug.cgi?id=110945

--- Comment #15 from CVS Commits <cvs-commit at gcc dot gnu.org> ---
The master branch has been updated by Jonathan Wakely <r...@gcc.gnu.org>:

https://gcc.gnu.org/g:cc3d7baf2741777e99567d4301802c99f5775619

commit r14-3306-gcc3d7baf2741777e99567d4301802c99f5775619
Author: Jonathan Wakely <jwak...@redhat.com>
Date:   Tue Aug 8 16:31:42 2023 +0100

    libstdc++: Optimize std::string::assign(Iter, Iter) [PR110945]

    Calling string::assign(Iter, Iter) with "foreign" iterators (not the
    string's own iterator or pointer types) currently constructs a temporary
    string and then calls replace to copy the characters from it. That means
    we copy from the iterators twice, and if the replace operation has to
    grow the string then we also allocate twice.

    By using *this = basic_string(first, last, get_allocator()) we only
    perform a single allocation+copy and then do a cheap move assignment
    instead of a second copy (and possible allocation). But that alternative
    has to be done conditionally, so that we don't pessimize the native
    iterator case (the string's own iterator and pointer types) which
    currently select efficient overloads of replace which will not allocate
    at all if the string already has sufficient capacity. For C++20 we can
    extend that efficient case to work for any contiguous iterator with the
    right value type, not just for the string's native iterators.

    So the change is to inline the code that decides whether to work in
    place or to allocate+copy (instead of deciding that via overload
    resolution for replace), and for the allocate+copy case do a move
    assignment instead of another call to replace.

    For C++98 there is no change, as we can't do an efficient move
    assignment anyway, so keep the current code.

    We can also simplify assign(initializer_list<CharT>) because the backing
    array for an initializer_list is always disjunct with *this, so most of
    the code in _M_replace is not needed.

    libstdc++-v3/ChangeLog:

            PR libstdc++/110945
            * include/bits/basic_string.h (basic_string::assign(Iter, Iter)):
            Dispatch to _M_replace or move assignment from a temporary,
            based on the iterator type.

Reply via email to