Is there any way to optimize c++ string += operator?

前端 未结 3 952
野趣味
野趣味 2021-01-24 12:33

English is not good, but please understand.

string str;
string str_base = "user name = ";
string str_user_input;
string str_system_message;
...

str = s         


        
相关标签:
3条回答
  • 2021-01-24 12:57

    I think this code does a lot of useless operations. Is there a way to optimize?

    Don't guess, but do measure by profiling.

    Perhaps (on Linux systems at least) with utilities such as gprof(1) or perf(1) or time(1), or functions related to time(7) such as clock_gettime(2). You'll find similar things for Windows and MacOSX and Android at least. Most computers have some hardware similar to HPET. See also OSDEV for more.

    If you use a recent GCC compiler, be sure to enable optimizations. So compile and link with at least g++ -Wall -pg -O2 -flto before using gprof(1). Learn also to use the GDB debugger (or another one) to observe the behaviour of your program (its operational semantics).

    You might be surprised by the optimizations a recent GCC 10 compiler is capable of (in summer 2020), since it will do inline expansion even when not asked with inline. If you happen to understand assembler code, try compiling your C++ code in foo.cc using a command line g++ -O3 -fverbose-asm -S foo.c then look inside the generated foo.s file.

    Of course, read a good C++ programming book and see this C++ reference website (and n3337, a C++ standard) . And read also the documentation of your C++ compiler (and linker).

    I think this code does a lot of useless operations. Is there a way to optimize?

    Leave such micro-optimizations to your C++ compiler.

    Ensure first that your code is correct, then spend efforts on profiling and optimizations.

    When you think of it, most computers spend their time doing a lot of useless operations. Read the blog of the late J.Pitrat and his Artificial beings book.

    As a software developer, your role is to balance your development efforts vs the computer time. Today, computers are most of the time cheaper than software developers.

    If raw performance is very important, spend your time in writing assembler code. If using Linux, read the Linux Assembly HowTo. Be prepared to be 10x times less productive than in C++....

    Consider also doing some metaprogramming and runtime code generation (e.g. with asmjit or libgccjit, or like SBCL does) if performance is important. Read more about partial evaluation and automatic program generation, read also the Dragon Book and some Introduction to Algorithms

    Another answer says:

    optimization problems look trivial at the first look

    Certainly not trivial. Be aware of Rice's theorem!

    I think this code does a lot of useless operations. Is there a way to optimize?

    Probably. Consider machine learning approaches to optimizations, like in MILEPOST GCC or Ctuning projects. Look (at least for inspiration) inside many open source projects (including CHARIOT, GCC, Clang, RefPerSys, Frama-C, Qt, ANTLR, SWIG) which generates or analyze C++ code.

    The important question is economical: is it worth your time (e.g. spending months of effort, perhaps writing your GCC plugin) to optimize your code by 1%? In some cases, it is worth the effort, in most cases it is not.

    0 讨论(0)
  • 2021-01-24 13:03

    Simplistically put, there are ways to optimize this:

    First, by using += instead of multiple + operations, you will avoid the creation of some temporary objects.

    That is, prefer to do:

    s += s1;
    s += s2;
    s += s3;
    

    instead of:

    s = s1 + s2 + s3;
    

    Second, the call (the += example above) could be preceded by adding up the sizes of the strings and reserving the memory in s.

    That said (I did mention it is a "simplistic" answer), here are some other considerations:

    • the language designers and compiler developers already spend much much time optimizing string operations, and you are unlikely to significantly optimize your code by micro-optimizations in a function dealing with strings and user input (unless the strings are inordinately large, unless this is code on the critical path and unless you are working in a very constrained system).

    • you probably got downvoted because it looks like you are focusing on the wrong problem to solve.

    • optimization problems look trivial at the first look, but until you set a performance goal and a way to measure current performance, you are likely to look for optimizations in the wrong place (which it looks like you are doing now).

    0 讨论(0)
  • 2021-01-24 13:15

    Your question says +=, but you're not using += anywhere. You are using only +.

    "+" is probably the most efficient way to concatenate strings. There are other ways, but it is unlikely that + is worse.

    As John Bollinger said, If all you need to do is output the concatenated result, then output the pieces directly:

    cout << str_base << str_user_input << "\n [system message :]" << str_system_message << endl;
    

    Or with C++20 (as Thomas Sablik says):

    std::format("{}{}\n [system message :]{}", str_base, str_user_input, str_system_message); otherwise: fmt::format("{}{}\n [system message :]{}", str_base, str_user_input, str_system_message);
    

    I would suggest trying to optimize other parts of your code instead (if you need to), since its unlikely you can do better than the language / compiler. forget about optimizing +.

    For another perspective, please refer to the answer for this question:

    Efficient string concatenation in C++

    0 讨论(0)
提交回复
热议问题