Search code examples
c++arraysperformancestdvector

Is there a way to avoid zeroing vector elements on resize, for the sake of performance?


Is there any way to make std::vector faster on reserving + resizing?

I would like to achieve the performance which would be somewhat equivalent to plain C arrays.

See the following code snippets:

TEST(test, vector1) {
   for (int i = 0; i < 50; ++i) {
      std::vector<int> a;
      a.reserve(10000000);
      a.resize(10000000);
   }
}

TEST(test, vector2) {
   for (int i = 0; i < 50; ++i) {
      std::vector<int> a(10000000);
   }
}

TEST(test, carray) {
   for (int i = 0; i < 50; ++i) {
      int* new_a = new int[10000000];
      delete[] new_a;
   }
}

First two tests are two times slower (4095 ms vs 2101 ms) and, obviously, that happens because std::vector is nulling the elements in it. Any ideas on how this could be avoided?

Or probably there is some standard (boost?) container that implements a fixed-size and heap-based array?


Solution

  • Well naturally the first 2 tests are slower. They explicitly go through the entire vector and call "int()" on each element. Edit: This has the effect of setting all the elements to "0".

    Just try reserving.

    There is some very relevant info to your question in this question i asked a while back:

    std::vector reserve() and push_back() is faster than resize() and array index, why?