传递右值参数作为参考的性能

请参阅下面的简单代码。我希望“#3”和“#4”具有相同的性能。

“#3”创建字符串,将其分配给变量(lvalue),然后通过引用(&)传递。 “#4”创建字符串(右值)并通过引用(&&)传递。

但是,“#4”慢大约5倍。与“#1”和“#2”一样慢。为什么是这样?

“#1”:调用带有byvalue lvalue参数的函数。 速度:2715

“#2”:调用带有byvalue rvalue参数的函数。 速度:2647

“#3”:调用具有l值参考参数的函数。 速度:566

“#4”:调用具有r值参考参数的函数。 速度:2638

码:

#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <chrono>
#include <time.h>
#include <exception>

void MyFunctionByValue(std::wstring text)
{
    text += L".";
}
void MyFunction(std::wstring& text)
{
    text += L".";
}
void MyFunction(std::wstring&& text)
{
    text += L".";
}

int main()
{
    unsigned int uint_LoopSize = 1000000;
    long lng_Start;
    std::wstring text = L"ABCDEFGHIJKLMNOPQRSTUVWXYZ_ABCDEFGHIJKLMNOPQRSTUVWXYZ_ABCDEFGHIJKLMNOPQRSTUVWXYZ_ABCDEFGHIJKLMNOPQRSTUVWXYZ_";

    std::wcout << L"#1: Function with byvalue lvalue parameter is called." << std::endl;
    lng_Start = clock();
    for (unsigned int i = 0; i < uint_LoopSize; i++)
    {
        text = L"ABCDEFGHIJKLMNOPQRSTUVWXYZ_ABCDEFGHIJKLMNOPQRSTUVWXYZ_ABCDEFGHIJKLMNOPQRSTUVWXYZ_ABCDEFGHIJKLMNOPQRSTUVWXYZ_";
        MyFunctionByValue(text);
    }
    std::wcout << L"Speed: " << clock() - lng_Start << std::endl;
    std::wcout << std::endl;

    std::wcout << L"#2: Function with byvalue rvalue parameter is called." << std::endl;
    lng_Start = clock();
    for (unsigned int i = 0; i < uint_LoopSize; i++)
    {
        MyFunctionByValue(L"ABCDEFGHIJKLMNOPQRSTUVWXYZ_ABCDEFGHIJKLMNOPQRSTUVWXYZ_ABCDEFGHIJKLMNOPQRSTUVWXYZ_ABCDEFGHIJKLMNOPQRSTUVWXYZ_");
    }
    std::wcout << L"Speed: " << clock() - lng_Start << std::endl;
    std::wcout << std::endl;

    std::wcout << L"#3: Function with l-value reference parameter is called." << std::endl;
    lng_Start = clock();
    for (unsigned int i = 0; i < uint_LoopSize; i++)
    {
        text = L"ABCDEFGHIJKLMNOPQRSTUVWXYZ_ABCDEFGHIJKLMNOPQRSTUVWXYZ_ABCDEFGHIJKLMNOPQRSTUVWXYZ_ABCDEFGHIJKLMNOPQRSTUVWXYZ_";
        MyFunction(text);
    }
    std::wcout << L"Speed: " << clock() - lng_Start << std::endl;
    std::wcout << std::endl;

    std::wcout << L"#4: Function with r-value reference parameter is called." << std::endl;
    lng_Start = clock();
    for (unsigned int i = 0; i < uint_LoopSize; i++)
    {
        MyFunction(L"ABCDEFGHIJKLMNOPQRSTUVWXYZ_ABCDEFGHIJKLMNOPQRSTUVWXYZ_ABCDEFGHIJKLMNOPQRSTUVWXYZ_ABCDEFGHIJKLMNOPQRSTUVWXYZ_");
    }
    std::wcout << L"Speed: " << clock() - lng_Start << std::endl;
    std::wcout << std::endl;

    return 0;
}

谢谢。

评论