Why do std::string operations perform poorly?

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

    The idiomatic C++ solution would be:

    #include 
    #include 
    #include 
    
    int main()
    {
        const int limit = 102 * 1024;
        std::string s;
        s.reserve(limit);
    
        const std::string pattern("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
    
        for (int i = 0; i < limit; ++i) {
            s += 'X';
            if (std::search(s.begin(), s.end(), pattern.begin(), pattern.end()) != s.end())
                std::cout << "Omg Wtf found!";
        }
        std::cout << "X's length = " << s.size();
        return 0;
    }
    

    I could speed this up considerably by putting the string on the stack, and using memmem -- but there seems to be no need. Running on my machine, this is over 10x the speed of the python solution already..

    [On my laptop]

    time ./test X's length = 104448 real 0m2.055s user 0m2.049s sys 0m0.001s

提交回复
热议问题