Hi all,

I've made a micro-benchmark to check how much the use of a character literal as 
an argument of std::string::find outperforms the use of a single character 
string literal:

#include <string>
#include <chrono>
#include <iostream>

int main() {
    int res = 0;
    std::string s(STRING_LITERAL);

    auto start = std::chrono::steady_clock::now();

    for(int i = 0; i < 10000000; i++) {
#ifdef CHAR_TEST
        res += s.find('A');
#else
        res += s.find("A");
#endif
    }

    auto end = std::chrono::steady_clock::now();

    std::chrono::duration<double> elapsed_seconds = end-start;
    std::cout << "elapsed time: " << elapsed_seconds.count() << "s\n";

    return res;
}

However, I have better performance with single character string literal when 
the std::string contains a small string and my program is compiled with -O3:

> (echo "char with small string" ; clang++ -DSTRING_LITERAL=\"BAB\" -DCHAR_TEST 
> -O3 -o bench_exe bench.cpp && ./bench_exe) ; (echo "string literal with small 
> string" ; clang++ -DSTRING_LITERAL=\"BAB\" -O3 -o bench_exe bench.cpp && 
> ./bench_exe)

char with small string
elapsed time: 0.0551678s
string literal with small string
elapsed time: 0.0493302s

I'm using the 8.0.0 version of clang:
> clang++ --version
clang version 8.0.0
Target: x86_64-unknown-linux-gnu
Thread model: posix

I can reproduce this results on all of my run. On average, the use of a single 
character string literal give me a 10% performance improvement.

My question is: is the use of a character literal as argument of 
std::string::find always faster whatever the optimization level and the size of 
the string?

Thanks.
_______________________________________________
cfe-users mailing list
cfe-users@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-users

Reply via email to