简体   繁体   中英

Is it better to declare a large vector as a member variable or a local variable inside a member function?

Let us say we need to process a large vector, which is only locally used inside a member function. Do we have any advantage in declaring it as a member function to save reallocation time? Because everytime a 10000 ints are being created and destroyed? Assume this is running in a mission critical embedded system. And the function is being called repeatedly!

class Foo {
  Foo() {
  
  }
  size_t update(int val) {
     vector<int> v(10000);
     for (int i = 0; i < 10000; ++i) {
        v[i] = i*i + val;
     }
     return compute(v);
  } 
  
};
class Foo {
  Foo() {
    v.resize(10000);
  }
  size_t update(int val) {
     for (int i = 0; i < 10000; ++i) {
        v[i] = i*i + val;
     } 
     return compute(v);
  } 
  private:
  vector<int> v; 
  
};

Yes, there might be a performance gain by declaring it as a member variable, but it might also be insignificant. As always: Measure, don't assume.

Constructing and destroying the ints is not the issue (this is a no-op), but the memory allocation and deallocation will be what changes.
This will be dependent on which allocator the system uses, and since you mention an embedded system that could be many different things.

There is however a challenge by declaring it a member variable: Can you guarantee that there are no parallel accesses to the vector?
If not, you will need to add mutexes etc. to guard the access, which could be worse performance-wise than the allocation.

A pattern often used in realtime systems is to pre-allocate all memory to be sure timing is constant during runtime.
In this case I would consider declaring the vector as a static variable outside the class (ie not in the header file), meaning it would be constructed before main() and there would be no runtime surprises.
This should however only be done if the class is only instantiated once, or you can otherwise guarantee that no parallel uses of the vector will happen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM