Home  >  Article  >  Backend Development  >  The pitfalls of size in stl

The pitfalls of size in stl

高洛峰
高洛峰Original
2016-11-22 15:12:391430browse

When I first joined the company last year, there was LRUCache in the company's basic library, and the implementation inside used std::list. But the function that calculates std::list directly uses the size() method in stl. As a result, during the stress test, the performance was stuck here.
Today, a colleague found another queue implementation in the basic library, which also used std::list. The size() method was also used when getting the number of elements.
Unfortunately, the company's basic library only exposes the header files, and it is impossible to check one by one whether this pit will exist in other places.

Let’s take a look at the implementation of the size() method in stl:

size_type    
  size() const
      { return std::distance(begin(), end()); }

The g++ version of the above code is 4.2.1

Obviously, the complexity is O(N). When there are many elements in the list, the calculation will be very slow. Therefore, when using std::list, you must remember to maintain a count yourself.


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn