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

前端 未结 3 981
野趣味
野趣味 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 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).

提交回复
热议问题