Home >Backend Development >C#.Net Tutorial >The pitfalls of size in stl
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.