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

前端 未结 3 953
野趣味
野趣味 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条回答
  •  旧时难觅i
    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++

提交回复
热议问题