How to convert std::string to lower case?

后端 未结 26 1563
旧时难觅i
旧时难觅i 2020-11-22 00:01

I want to convert a std::string to lowercase. I am aware of the function tolower(), however in the past I have had issues with this function and it

26条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 00:44

    As far as I see Boost libraries are really bad performance-wise. I have tested their unordered_map to STL and it was average 3 times slower (best case 2, worst was 10 times). Also this algorithm looks too low.

    The difference is so big that I am sure whatever addition you will need to do to tolower to make it equal to boost "for your needs" will be way faster than boost.

    I have done these tests on an Amazon EC2, therefore performance varied during the test but you still get the idea.

    ./test
    Elapsed time: 12365milliseconds
    Elapsed time: 1640milliseconds
    ./test
    Elapsed time: 26978milliseconds
    Elapsed time: 1646milliseconds
    ./test
    Elapsed time: 6957milliseconds
    Elapsed time: 1634milliseconds
    ./test
    Elapsed time: 23177milliseconds
    Elapsed time: 2421milliseconds
    ./test
    Elapsed time: 17342milliseconds
    Elapsed time: 14132milliseconds
    ./test
    Elapsed time: 7355milliseconds
    Elapsed time: 1645milliseconds
    

    -O2 made it like this:

    ./test
    Elapsed time: 3769milliseconds
    Elapsed time: 565milliseconds
    ./test
    Elapsed time: 3815milliseconds
    Elapsed time: 565milliseconds
    ./test
    Elapsed time: 3643milliseconds
    Elapsed time: 566milliseconds
    ./test
    Elapsed time: 22018milliseconds
    Elapsed time: 566milliseconds
    ./test
    Elapsed time: 3845milliseconds
    Elapsed time: 569milliseconds
    

    Source:

    string str;
    bench.start();
    for(long long i=0;i<1000000;i++)
    {
        str="DSFZKMdskfdsjfsdfJDASFNSDJFXCKVdnjsafnjsdfjdnjasnJDNASFDJDSFSDNJjdsanjfsdnfjJNFSDJFSD";
        boost::algorithm::to_lower(str);
    }
    bench.end();
    
    bench.start();
    for(long long i=0;i<1000000;i++)
    {
        str="DSFZKMdskfdsjfsdfJDASFNSDJFXCKVdnjsafnjsdfjdnjasnJDNASFDJDSFSDNJjdsanjfsdnfjJNFSDJFSD";
        for(unsigned short loop=0;loop < str.size();loop++)
        {
            str[loop]=tolower(str[loop]);
        }
    }
    bench.end();
    

    I guess I should to the tests on a dedicated machine but I will be using this EC2 so I do not really need to test it on my machine.

提交回复
热议问题