Reuse container or announce new

Suppose you need to use the STL container (set, map, queue) several times. Which overall approach would be better?

  • Create a container every time.
  • Use the same global object every time, but spend some time cleaning it.
// Option 1 void foo() { set<int> S; //creating a new S each time foo is called. //use S... } // Option 2 set<int> S; void foo() { S.clear(); //use S... } 
+3
c ++ performance stl
source share
2 answers

Without performing a performance test, I would tell you that it is intuitively clear that Options 2 (reuse) is slightly faster because you do not create or destroy the container each time. When you destroy a container, it necessarily clears it, otherwise there will be a memory leak.

However, performing a performance test gives different results:

  • For std :: list, it seems that clear takes longer than the destructor.
  • For std :: set, the results were almost identical.
  • For std :: map, the results were close, but option 1 (destructor) was a bit faster.
  • For std :: vector, the results were like a list (although a vector vector is much faster)

So overall, it seems that parameter1 is a little faster. I worked with VS2012, YMMV

+3
source share

Assuming you don't have to deal with multi-threaded issues, case 2 is probably better. Mostly because for some standard containers, lib clearly avoids memory allocation. In particular, see the documentation for the std :: vector cleanup function .

Reset does not cause memory redistribution, vector capacity does not change.

0
source share

All Articles