问题
What's the fastest way to "clear" a large STL container? In my application, I need to deal with large size std::map
, e.g., 10000 elements.
I have tested the following 3 methods to clear a std::map
.
- Create a new container every time I need it.
- Calling
map::clear()
method. - Calling
map::swap()
method.
It seems that ::swap()
gives the best result. Can anyone explain why this is the case, please? Is it safe to say that using map::swap()
method is the proper way to "clear" a std::map? Is it the same for other STL containers, e.g., set
, vector
, list
, etc.
m_timer_start = boost::posix_time::microsec_clock::local_time();
// test_map.clear();
test_map.swap(test_map2);
for (int i = 0; i< 30000; i++){
test_map.insert(std::pair<int, int>(i, i));
}
// std::map<int, int> test_map_new;
// for (int i = 0; i< 30000; i++){
// test_map_new.insert(std::pair<int, int>(i, i));
// }
m_timer_end = boost::posix_time::microsec_clock::local_time();
std::cout << timer_diff(m_timer_start, m_timer_end).fractional_seconds() << std::endl; // microsecond
回答1:
You aren't properly testing the swap
case. You need for the swap-to map to be destroyed in order to account for all of the time. Try one of these:
{ std::map<something, something_else> test_map2;
test_map.swap(test_map2);
} // test_map2 gets destroyed at the closing brace.
or
// temporary gets destroyed at the semi-colon
std::map<int, int>().swap(test_map);
回答2:
Are you asking this because you're having a performance problem and you have identified that your program is spending too much time clearing your maps? If you haven't done this then just use map::clear() or create new local variables each time, whichever is most natural and direct for your program. The swap trick is an optimization and there's little point in wasting time optimizing unless you're certain you need to, based on experience.
If you have identified a performance issue then you've already got the tool to determine which of your methods best addresses it.
来源:https://stackoverflow.com/questions/10097772/c-stl-container-clear-swap