llvm / llvm-project

The LLVM Project is a collection of modular and reusable compiler and toolchain technologies.
http://llvm.org
Other
28.61k stars 11.82k forks source link

comparison with short (< 16 chars) local `const std::string` is slower when it is `static` #60165

Open firewave opened 1 year ago

firewave commented 1 year ago

Split from #58002.

#include <string>

#define LITERAL_S "012345678901234"
#define LITERAL_L "0123456789012345"

bool cmp3_s(const std::string& s)
{
    const std::string s_s(LITERAL_S);
    return s == s_s;
}

bool cmp4_s(const std::string& s)
{
    static const std::string s_s(LITERAL_S);
    return s == s_s;
}

bool cmp3_l(const std::string& s)
{
    const std::string s_s(LITERAL_L);
    return s == s_s;
}

bool cmp4_l(const std::string& s)
{
    static const std::string s_s(LITERAL_L);
    return s == s_s;
}

https://quick-bench.com/q/A3FPfNV6Cds2TwwBvSRwT6klxLg

This applies to all strings with less than 16 characters.

This does not happen with GCC where static is always faster no matter the length: https://quick-bench.com/q/hPor-y8JDwcMBEnT_oOv79nF43g https://quick-bench.com/q/4Ef2dOfaBuhCd0QkKBRVVCXamjI

firewave commented 1 year ago

Using -O3 improves things but it is still slower: https://quick-bench.com/q/q1dTqCGNfLvOLHW5ZI_vV4Io91c

Only starting with C++-20 it yields the expected result: https://quick-bench.com/q/DoPeAkL3TzHA_aw_RrykbZyRgOc