c++ - 小字符串优化(SSO)和移动语义

标签 c++ performance c++11

std::string test = "small_string";

std::string test2_1 = test;   // line 1

std::string test2_2 = std::move(test); // line 2

您好,我很好奇哪个版本的字符串创建速度快。 test2_1 还是 test2_2

我正在研究 std::string 的 VC++ 版本的实现,发现 test2_1 版本将调用 memcpy(_First1, _First2, _Count) )test2_2 将调用 memmove(_First1, _First2, _Count)),我只是想知道如果我想让我的代码运行得更快,哪个更好。

============================================= ===============

嗨,我刚刚做了一些测试,有些东西我无法理解......这是我的测试代码:

{
    Timer t;
    for (int i = 0; i < 1000000; i++){
        char s[] = "small_string";
        char t[10];

        memcpy(&t, &s, 10);
        //std::cout << t << std::endl;
    }

    std::cout << "test, memcpy: " << t.elapsed() << " second" << std::endl;
}


{
    Timer t;
    for (int i = 0; i < 1000000; i++){
        char s[] = "small_string";
        char t[10];
        memmove(&t, &s, 10);
       // std::cout << t << std::endl;
    }

    std::cout << "test, memmove: " << t.elapsed() << " second" << std::endl;
}


{
    Timer t;
    for (int i = 0; i < 1000000; i++){

        std::string test = "small_string";
        std::string test2_1 = test;   // line 1
    }

    std::cout << "test, str copy: " << t.elapsed() << " second" << std::endl;
}


{
    Timer t;
    for (int i = 0; i < 1000000; i++){

        std::string test = "small_string";
        std::string test2_2 = std::move(test); // line 2
    }
    std::cout << "test, str move: " << t.elapsed() << " second" << std::endl;
}

结果是:(调试构建)

测试,memcpy:0.0090005 秒

测试,内存移动:0.0110006 秒

测试,str复制:4.92528秒

测试,str move:4.52926 秒

我知道 memcpy 应该比 memmove 更快,我的前两个测试用例证明了这一点。但是 std::string 的结果是不同的……移动版本比复制版本快。我不知道为什么即使查看 std::string 的实现,我也没有找到任何可以说服我这应该发生的东西。

============================================= ========

结果:(发布版本)

测试,memcpy:0 秒

测试,内存移动:0.0080004 秒

测试,str复制:0.0330019秒

测试,str 移动:0.0290017 秒

最佳答案

hi, i am curious about which version of string create is fast. test2_1 or test2_2?

这似乎是过早优化的明显例子。这两种形式甚至不等同,所以问哪个更快是荒谬的。

编写做正确事情的代码,只有在出现性能问题时才担心愚蠢的微优化。

第 1 行保留 test 不变,因此它保持相同的值。第 2 行修改 test 使其处于未指定状态。

如果您的代码在创建另一个字符串后不依赖于 test 的值,那么您应该使用 std::move 因为它表达了所需的语义(如果字符串不适合小字符串缓冲区,它肯定会更快)。

如果您的代码随后关心test 的值,那么不要使用std::move,只需复制即可。

对苹果和橙子之间的差异进行基准测试是浪费时间。

在调试版本中对微小差异进行基准测试是在浪费大量时间。如果您关心性能,则需要启用优化。

关于c++ - 小字符串优化(SSO)和移动语义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30617906/

相关文章:

c++ - 如何创建动态大小的链表数组?

c++ - 我该如何修复错误??错误 : expected ";" before "factorial"? 它在第 16 行中说

c++ - visual studio 中智能指针对象的自定义 View ?

c++ - 自动矢量化对齐

c++ - 哪种是产生线程的最佳方法?

mysql - 多个 MAX() 函数,每个函数具有不同的条件

c++ - 最快的 C++ map ?

c# - 方法的执行时间在增加,为什么会这样?

C++ 和动态类型语言

c++ - 获取正确的 value_type