小编chi*_*ice的帖子

使用短字符串优化似乎比 gcc 9.4.0 中的分配慢

我正在测试下面的代码

#include <string>
int main(int argc, const char *argv[])
{
    const size_t size = strtoull(argv[1], nullptr, 10);
    for (int i = 0; i < 100000000; ++i)
    {
        std::string str;
        str.reserve(size);
        for (size_t j = 0; j < size; ++j)
        {
            str += 'x';
        }
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我用-O3编译它

g++ string-append.cpp -O3 -o string-append
Run Code Online (Sandbox Code Playgroud)

现在,当使用参数运行时,15程序看起来比使用参数运行时慢16

$ time ./string-append 15

real    0m4.342s
user    0m4.342s
sys     0m0.000s

$ time ./string-append 16

real    0m3.112s
user    0m3.112s
sys     0m0.000s
Run Code Online (Sandbox Code Playgroud)

我已经通过 …

c++ g++

5
推荐指数
0
解决办法
352
查看次数

标签 统计

c++ ×1

g++ ×1