Why do std::string operations perform poorly?

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

    It's not that std::string performs poorly (as much as I dislike C++), it's that string handling is so heavily optimized for those other languages.

    Your comparisons of string performance are misleading, and presumptuous if they are intended to represent more than just that.

    I know for a fact that Python string objects are completely implemented in C, and indeed on Python 2.7, numerous optimizations exist due to the lack of separation between unicode strings and bytes. If you ran this test on Python 3.x you will find it considerably slower.

    Javascript has numerous heavily optimized implementations. It's to be expected that string handling is excellent here.

    Your Java result may be due to improper string handling, or some other poor case. I expect that a Java expert could step in and fix this test with a few changes.

    As for your C++ example, I'd expect performance to slightly exceed the Python version. It does the same operations, with less interpreter overhead. This is reflected in your results. Preceding the test with s.reserve(limit); would remove reallocation overhead.

    I'll repeat that you're only testing a single facet of the languages' implementations. The results for this test do not reflect the overall language speed.

    I've provided a C version to show how silly such pissing contests can be:

    #define _GNU_SOURCE
    #include 
    #include 
    
    void test()
    {
        int limit = 102 * 1024;
        char s[limit];
        size_t size = 0;
        while (size < limit) {
            s[size++] = 'X';
            if (memmem(s, size, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 26)) {
                fprintf(stderr, "zomg\n");
                return;
            }
        }
        printf("x's length = %zu\n", size);
    }
    
    int main()
    {
        test();
        return 0;
    }
    

    Timing:

    matt@stanley:~/Desktop$ time ./smash 
    x's length = 104448
    
    real    0m0.681s
    user    0m0.680s
    sys     0m0.000s
    

提交回复
热议问题