(Performance perspective) The performance of pass by value is not necessarily lower than pass by reference)

       When most programmers write code or teach others to write code, as long as other people use pass by value instead of pass by reference for function parameters, they will sneer and feel that this is a sign of lack of strength. Some people know that pass by reference cannot be used entirely because it sometimes leads to security issues. But basically no one knows that in some cases, the performance of pass by value is not only not low, but also higher than that of pass by reference.

       1.Performance perspective

       If within the function, a copy of the received parameters is taken, and then the copy is used for processing, then a higher performance method is to directly use pass by value in the function's receiving parameters. Because the compiler may generate more efficient code at this time.

For example, the following code

void printString(std::string& s)
{
	std::string cur = s;
	cur += "dd";
}

void printHighString(std::string s)
{
	s += "dd";
}

static void BM_demo1(benchmark::State& state) {
	std::string ss("hello world");
	for (auto _ : state)
		printString(ss);
}
BENCHMARK(BM_demo1)->Iterations(1000000); //用于注册测试函数
static void BM_demo2(benchmark::State& state) {
	std::string ss("hello world");
	for (auto _ : state)
		printHighString(ss);
}
BENCHMARK(BM_demo2)->Iterations(1000000); //用于注册测试函数
// Register the function as a benchmark


BENCHMARK_MAIN(); //程序入口

        You can see that the printString function uses pass by reference, and the printHighString function uses pass by value. According to ordinary people's understanding, printString must have high performance here! , it is useless to just think who has high performance, so I use google-benchmark here to get the results.

        You can see that the running time of the printHighString function is not only not slow, it is even faster than the printString function.

        Why is there such a counterintuitive result? This is because they ignored one of the most important issues. The printString function takes a copy of the parameters passed by reference and then operates the copy. The printHighString function passes parameters by value, and the compiler can optimize it.

        If we cancel the copy operation in the printString function, we will get the following results

This is indeed in line with everyone's inherent understanding of the performance gap between pass by reference and pass by value.

Guess you like

Origin blog.csdn.net/qq_51710331/article/details/132646951