vector::size() in bits/stl_vector.h is currently implemented as
size_type
size() const
{ return size_type(end() - begin()); }
A faster implementation is
size_type
size() const
{ return _M_impl._M_finish - _M_impl._M_start; }
Which avoids the temporary iterators' life cycles
and operator- calls.
I tried a simple timing test on both implementations,
and the latter appears to be 10x faster:
(11:35:56)(charles xyzzy)(~): cat test.cc
#include <vector>
int main () {
std::vector<int> x (100);
unsigned long l = 0;
const unsigned long iterations = 100000000;
for (unsigned long i=0; i<iterations; ++i)
l += x.size ();
return 0;
}
(11:35:58)(charles xyzzy)(~): g++ -o test test.cc -lstdc++
(11:36:05)(charles xyzzy)(~): time ./test
real 0m3.692s
user 0m3.676s
sys 0m0.004s
(11:36:10)(charles xyzzy)(~): cat test2.cc
#include <vector>
int main () {
std::vector<int> x (100);
unsigned long l = 0;
const unsigned long iterations = 100000000;
for (unsigned long i=0; i<iterations; ++i)
l += x._M_impl._M_finish - x._M_impl._M_start;
return 0;
}
(11:36:13)(charles xyzzy)(~): g++ -o test2 test2.cc -lstdc++
(11:36:19)(charles xyzzy)(~): time ./test2
real 0m0.342s
user 0m0.336s
sys 0m0.004s
--
Summary: std::vector::size() 10x speedup (patch)
Product: gcc
Version: unknown
Status: UNCONFIRMED
Severity: enhancement
Priority: P3
Component: libstdc++
AssignedTo: unassigned at gcc dot gnu dot org
ReportedBy: charles at rebelbase dot com
http://gcc.gnu.org/bugzilla/show_bug.cgi?id=30203