Efficient way to return a stl vector by value from a function

This is an extension question from Efficient way to return std :: vector in C ++

#include <cstdio>
#include <vector>
#include <chrono>

std::vector<int> func1() {
    std::vector<int> v;
    v.reserve(1e6);
    for (int i = 0; i < 1e6; i++) v.emplace_back(i);
    return v;
}

std::vector<int> func2() {
    std::vector<int> v;
    v.reserve(1e6);
    for (int i = 0; i < 1e6; i++) v.emplace_back(i);
    return std::move(v);
}

int main() {
    auto start1 = std::chrono::steady_clock::now();
    std::vector<int> v1 = func1();
    auto end1 = std::chrono::steady_clock::now();
    printf("%d\n", std::chrono::duration_cast<std::chrono::nanoseconds>(end1-start1).count());

    auto start2 = std::chrono::steady_clock::now();
    std::vector<int> v2 = func2();
    auto end2 = std::chrono::steady_clock::now();
    printf("%d\n", std::chrono::duration_cast<std::chrono::nanoseconds>(end2-start2).count());

/*
    auto start3 = std::chrono::steady_clock::now();
    std::vector<int> v3 = v2;
    auto end3 = std::chrono::steady_clock::now();
    printf("%d\n", std::chrono::duration_cast<std::chrono::nanoseconds>(end3-start3).count());
*/

    return 0;
}

In method 2, I explicitly tell the compiler that I want to move, instead of copying the vector, but running the code several times shows that method 1 sometimes surpasses method 2, and even if method 2 wins, it is not strong.

Method 3 is consistently the best. How to emulate method 3 when I should return from function? (No, I can not follow the link)

Using gcc 6.1.0

+4
source share
1 answer

1 - Named Return Value Optimization (NRVO). , . NRVO, , 2.

2 - NRVO std::vector. , , 1.

3 - , , , - . , ( , emplaces) - , 1 2.

NRVO? : std::vector<int> v, . rvalue, , .

- :

std::vector<int> func1(std::vector<int>& hidden) {
     hidden.emplace_back(stuff);
     return;
}
+9

Source: https://habr.com/ru/post/1661796/


All Articles