Why is the vector range constructer 10 times faster than the fill constructor?

I've tested the following two ways of filling a vector with 100'000 elements:

#include <iostream>
#include <vector>
#include <chrono>

using std::cout;
using std::endl;
using std::vector;
using std::chrono::high_resolution_clock;
using std::chrono::duration_cast;

int main()
{
    const int n = 100'000;

    cout << "Range constructor: " << endl;
    high_resolution_clock::time_point t0 = high_resolution_clock::now();

    int nums10[n];
    for (int i = 0; i < n; ++i) {
        nums10[i] = i;
    }
    vector<int> nums11(nums10, nums10 + n);

    high_resolution_clock::time_point t1 = high_resolution_clock::now();
    cout << "Duration: " << duration_cast<std::chrono::microseconds>(t1 - t0).count() << endl;


    cout << "Fill constructor: " << endl;
    t0 = high_resolution_clock::now();
    
    vector<int> nums1(n);
    for (int i = 0; i < n; ++i) {
        nums1[i] = i;
    }

    t1 = high_resolution_clock::now();
    cout << "Duration: " << duration_cast<std::chrono::microseconds>(t1 - t0).count() << endl;;
}

In my case, the range constructor runs almost 10 times faster (600 microseconds vs ~5000 microseconds).

Why would there be any performance difference here at all? To my understanding there is an equal amount of assignment operations. Using the range constructor, 100'000 elements are assigned to the array, and then all of them are copied to the vector.

Should this not be identical to the fill constructor, in which 100'000 elements are first default initialized to 0, and then all of them are assigned their "real" values in the for loop?



Read more here: https://stackoverflow.com/questions/67014099/why-is-the-vector-range-constructer-10-times-faster-than-the-fill-constructor

Content Attribution

This content was originally published by J. Grohmann at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: