I have written a simple program to test the performance of size() method in STL list and STL vector. For a STL list with 10M integers, it takes 0.17 sec. to get the size. However, for a STL vector with 10M integers, it takes 0.4 micro sec to get the size() in same machine.
There are some suggestions:
- Use vector instead of list.
- If the application need to check whether the list is empty or not, uses "list.emtpy()" instead of "list.size() != 0".
- use an extra counter variable to counting the size of a list.
1 comment:
Actually, it depends on which STL you are using. Microsoft Visual Studio V6 implements size() as {return (_Size); } whereas gcc (at least in versions 3.3.2 and 4.1.0) do it as
{ return std::distance(begin(), end()); }
The first has constant speed, the second has o(N) speed
Post a Comment