vector::operator[](size_type) in bits/stl_vector.h is currently implemented as
reference
operator[](size_type __n)
{ return *(begin() + __n); }
const_reference
operator[](size_type __n) const
{ return *(begin() + __n); }
A faster implementation would be:
reference
operator[](size_type __n)
{ return _M_impl._M_start[__n]; }
const_reference
operator[](size_type __n) const
{ return _M_impl._M_start[__n]; }
I tried a simple timing test on both implementations,
and the latter appears to be 10x faster:
(11:59:43)(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[50];
return 0;
}
(12:00:14)(charles xyzzy)(~): g++ -o test test.cc -lstdc++
(12:00:22)(charles xyzzy)(~): time ./test
real 0m2.956s
user 0m2.948s
sys 0m0.008s
(12:00:27)(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_start[50];
return 0;
}
(12:00:31)(charles xyzzy)(~): g++ -o test2 test2.cc -lstdc++
(12:00:39)(charles xyzzy)(~): time ./test2
real 0m0.228s
user 0m0.228s
sys 0m0.000s
--
Summary: std::vector operator[] 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=30204