zeralight
zeralight

Reputation: 710

c++ big vector in function called multiple times

I have a function that creates a big vector for its internal work. Say we need also to call this function many times. What's the best way to handle the memory creation/destruction of the vector (factors are performance, Quality of Code..)

Method 1:

void f(int n) {
    vector<int> v(n);
 }

 int main() {
     for (int i = 0; i < 1000000; ++i) f(10000000);
 }

Method 2:

void f(int n) {
    static vector<int> v;
    v.reserve(99999999); // say this is the maximum possible size

    v.resize(n);
}

 int main() {
     for (int i = 0; i < 1000000; ++i) f(10000000);
 }

Method 2 is definitely faster than Method 1, but it looks ugly. What would be the best approach

Upvotes: 1

Views: 238

Answers (3)

g11101
g11101

Reputation: 11

v.reserve() //deals with capacity.
v.resize(n) //deals with size.

In Method 2, what the static vector is experiencing, is just changing the size, however, the reserved space is more than than the size, therefore there is no change in the capacity, and when you are iterating through the loop it just increases by one. Therefore, the size just gets increased by one every time. The capacity has no change. Usually if resize is called on an empty vector of int, the vector elements at that resize range would be initialized to 0.

On Method 1, the vector is being created with a size of n, but with the most proximate n<2^k integer value as a capacity (for example if n=100, then capacity 128, when n=200, capacity 256, and so on). Also, when you are calling the method one, you are creating and destroying each time the function goes out of scope. It is to note that the vector is empty, as it does not have any values.

In Method 2, the vector is static and remains.

You may want to read:

Reserve

Capacity

Also, if you are having the vector reserve memory, and assuming you may not be bothered by the amount of memory, a pre-allocation of memory, with constant insertions by amortized analysis would have a Big-O(1), for each operation.

Upvotes: 0

user3196144
user3196144

Reputation: 307

According to your example, your vector size is same so why not create only one vector?

  using namespace std;
    void f(vector<int>& v) {
        // Do something with vector
    }
    int main() {

        int n = 10000000;
        vector<int> v(n);

        for (int i = 0; i < 1000000; ++i)
            f(v);
    }

Upvotes: 0

Sam Varshavchik
Sam Varshavchik

Reputation: 118340

Turn the function into a class with an operator().

class f_class {

   std::vector<int> v;

public:

   f_class()
   {
        v.reserve(99999999);
   }

   void operator()(int n)
   {
        v.resize(n);
        // Whatever the original f() did
   }
};

int main() {

     f_class f;

     for (int i = 0; i < 1000000; ++i) f(i);
}

Upvotes: 3

Related Questions