Why do std::string operations perform poorly?

后端 未结 12 1664
误落风尘
误落风尘 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:08

    What you are missing here is the inherent complexity of the find search.

    You are executing the search 102 * 1024 (104 448) times. A naive search algorithm will, each time, try to match the pattern starting from the first character, then the second, etc...

    Therefore, you have a string that is going from length 1 to N, and at each step you search the pattern against this string, which is a linear operation in C++. That is N * (N+1) / 2 = 5 454 744 576 comparisons. I am not as surprised as you are that this would take some time...

    Let us verify the hypothesis by using the overload of find that searches for a single A:

    Original: 6.94938e+06 ms
    Char    : 2.10709e+06 ms
    

    About 3 times faster, so we are within the same order of magnitude. Therefore the use of a full string is not really interesting.

    Conclusion ? Maybe that find could be optimized a bit. But the problem is not worth it.

    Note: and to those who tout Boyer Moore, I am afraid that the needle is too small, so it won't help much. May cut an order of magnitude (26 characters), but no more.

提交回复
热议问题