Hédi Ghédiri Hédi Ghédiri - 1 month ago 6
C++ Question

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

Answer

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);
}
Comments