Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why compiler can not optimize std::string concat?

I try such simple code:

#include <cstdio>
#include <string>

int main()
{
   const std::string s = std::string("a") + "b";
   puts(s.c_str());
   return 0;
 }

I expect that compiler(gcc 4.8.2/clang 3.5.0) optimize such code to

 int main()
 {
   puts("ab");
   return 0;
 }

But I can not get such result, I try different options like "-Ofast", "-flto", "-static-libstdc++", but always see in disassembler output three functions call:

...
callq  0x4017e0 <_ZNSsC2EPKcRKSaIcE>
... 
callq  0x401690 <_ZNSs6appendEPKc>
...
callq  0x401490 <_ZNSs4_Rep10_M_disposeERKSaIcE>

The first one is call to std::basic_string, std::allocator >::basic_string(char const*, std::allocator const&).

So are any compiler around, that can optmize such code to just puts("ab"); or at least to "std::string s("ab");"?

And if there are no such compiler, what make such optimization difficult to implement?

Update About real world usage. I see/saw many places in real code with such pattern:

  std::string s = std::string(string_const1) + string_const2 + string_variable + string_const3;

And if performance is important, of course it is possible to rewrite such code in more optimal ways.

But modern compilers do great jobs to optimize code. And gcc, for example have __builtin functions for malloc/free/strcpy/strcat and so on. And if std::basic_string from libstdc++ from gcc use them this functions(malloc,free,strcpy,strcat) for part of implementation, why not predict the result of functions usage and give answer.

like image 743
fghj Avatar asked Nov 04 '14 00:11

fghj


1 Answers

std::string involves dynamic allocation of storage and, in most cases, an extremely complex implementation and can therefore not be reduced to compile-time semantics, no matter how well the compiler has constant folding down to a fine art.

However: If your string is actually declared like this why didn't you use a char array in the first place but chose string? If you need to work with some strings to produce others, there are still tools that can do that job with char arrays, especially since C++11 introduced variadic templates and constexpr. A future version of C++ will hopefully also introduce std::string_literal to further ease that.

like image 108
Columbo Avatar answered Oct 01 '22 18:10

Columbo