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

            Bug ID: 122727
           Summary: Efficient String Concatenation
           Product: gcc
           Version: 15.2.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: terra at gnome dot org
  Target Milestone: ---

Consider the code...

#include <string>

std::string
oink(std::string const &s, char c, std::string_view sv)
{
    return s + c + std::string(sv);
}

(the explicit construction of a string from a string_view is C++'s fault for
not defining an appropriate operator+)

The code generated from this is fairly bad: 
https://godbolt.org/z/6f1MKbPqh

It's basically what you would expect if you just expanded the templates: it
allocates and frees temporaries with a bit of local optimization.

I believe that the C++ front end should recognize concatenation of strings and
generate much simpler and far more efficient code.  Basically the equivalent of

(1) size = s.size() + 1 + sv.size();
(2) allocate string of size bytes, plus room for \0. (or use short-string)
(3) memcpy s's contents into place
(4) put c into place
(5) memcpy sv's contents into place
(6) add terminating \0

One allocation only, no destructor calls, all moving of characters directly
into their final location.  I.e., roughly what java would do with its
StringBuilder class.  

I'm not sure that's possible for the optimizer which is why I see this as a
front end issue.

Reply via email to