Which is faster: recreate or clean ()?

I have a question about std :: vector <> performance in C ++. Is it easy to reuse the same vector by calling its clear () method, or does it recreate the vector faster?

In the following example, there is no real life code, this is only to clearly indicate that the question is:

//Example ONE: is this faster std::vector<int> foo; for(int i = 0; i < 100; ++i) { foo.clear(); for(int j = 0; j < 100; ++j) { foo.push_back(i+j); } } //Example TWO: or is that faster? for(int i = 0; i < 100; ++i) { std::vector<int> foo; for(int j = 0; j < 100; ++j) { foo.push_back(i+j); } } 
+6
source share
7 answers

clear() cannot contractually free vector by its contract, but simply sets the internal size flag to 0 , so the method will be faster.

+7
source

It depends on the std::vector implementation in the C ++ standard library that you use, but most likely the first case will be faster, because most implementations do not actually release the allocated memory when calling std::vector::clear . Thus, the first does not perform re-allocations after the inner loop has been executed for the first time.

+2
source

Yes. Not. The first is likely faster. It depends. The only useful answer is profiling your own code in your own environment.

Try profiling your code to see what happens. Compiling your program on ideone shows that for one specific compiler / os / machine / run your first example is 4 times faster.

And this program shows an intermediate solution that goes faster than # 2, slower than # 1, for this particular compiler / os / machine / start.

+1
source

Example 2 has duplicate heap allocations for an array inside std :: vector. Example 1 is faster because it avoids multiple memory allocation on the heap if the vector should not change internally.

0
source

You will have to run tests for your compiler. The clear() and 'allocate' methods are implementation dependent.

0
source

Scott Myers recommends a trick to clean the vector and reduce its ability to minimize implementation. :

 std::vector<int>().swap( foo ); 

It will also be faster than repeating through a vector with a manual loop to restore its contents.

0
source

In this particular case, the reuse case is likely to be faster on most machines. You store primitive data that does not need to be destroyed (or even have a destructor). On the other hand, if the vector contains objects other than POD, each element will be destroyed by calling clear . On the other hand, all the accumulated data will eventually need to be destroyed.

0
source

Source: https://habr.com/ru/post/896898/


All Articles