Why do std::string operations perform poorly?

后端 未结 12 1682
误落风尘
误落风尘 2020-12-22 23:43

I made a test to compare string operations in several languages for choosing a language for the server-side application. The results seemed normal until I finally tried C++,

12条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-23 00:25

    My first thought is that there isn't a problem.

    C++ gives second-best performance, nearly ten times faster than Java. Maybe all but Java are running close to the best performance achievable for that functionality, and you should be looking at how to fix the Java issue (hint - StringBuilder).

    In the C++ case, there are some things to try to improve performance a bit. In particular...

    • s += 'X'; rather than s += "X";
    • Declare string searchpattern ("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); outside the loop, and pass this for the find calls. An std::string instance knows it's own length, whereas a C string requires a linear-time check to determine that, and this may (or may not) be relevant to std::string::find performance.
    • Try using std::stringstream, for a similar reason to why you should be using StringBuilder for Java, though most likely the repeated conversions back to string will create more problems.

    Overall, the result isn't too surprising though. JavaScript, with a good JIT compiler, may be able to optimise a little better than C++ static compilation is allowed to in this case.

    With enough work, you should always be able to optimise C++ better than JavaScript, but there will always be cases where that doesn't just naturally happen and where it may take a fair bit of knowledge and effort to achieve that.

提交回复
热议问题