>> Indeed, but you can remove bounds checking in VS (and it's not required to do bounds checking according to the standard anyway), and in Release, it does very well inline the operator [].
interesting. after running a performance test on a stripped down vector class (inlined, with no bounds checking) it still turned out to be noticably slower than an array.
Code:
#include <iostream>
#include <iomanip>
#include <vector>
#include <ctime>
namespace test {
template < typename Type >
class vector
{
public:
vector( size_t length = 0 )
: data_( 0 ), length_( 0 )
{
resize( length );
}
inline Type &
operator [ ] ( size_t index )
{
return data_[ index ];
}
inline Type const &
operator [ ] ( size_t index ) const
{
return data_[ index ];
}
void
resize( size_t length )
{
free( );
data_ = new Type[ length_ = length ];
}
void
free( void )
{
delete [] data_;
length_ = 0;
}
virtual
~vector( void )
{
free( );
}
protected:
vector( vector const & );
Type * data_;
size_t length_;
};
} // namespace test
const int size = 100;
class B
{
public:
virtual int sum() = 0;
};
class V : public B
{
private:
std::vector < std::vector <int> > vec;
public:
V()
{
for(int i = 0; i < size; i++)
{
vec.push_back(std::vector<int>(0));
for(int j = 0; j < size; j++)
{
vec[i].push_back(i * j);
}
}
}
virtual int sum() {
int s = 0;
for(int i = 0; i < size; i++)
for(int j = 0; j < size; j++)
s += vec[i][j];
return s;
}
};
class V2 : public B
{
private:
test::vector < test::vector <int> > vec;
public:
V2()
: vec( size )
{
for(int i = 0; i < size; i++)
{
vec[i].resize(size);
for(int j = 0; j < size; j++)
{
vec[i][j] = i * j;
}
}
}
virtual int sum() {
int s = 0;
for(int i = 0; i < size; i++)
for(int j = 0; j < size; j++)
s += vec[i][j];
return s;
}
};
class A : public B
{
private:
int arr[size][size];
public:
A()
{
for(int i = 0; i < size; i++)
{
for(int j = 0; j < size; j++)
{
arr[i][j] = i * j;
}
}
}
int sum() {
int s = 0;
for(int i = 0; i < size; i++)
for(int j = 0; j < size; j++)
s += arr[i][j];
return s;
}
};
int func(B *b)
{
return b->sum();
}
void timeIt(char *name, int (*f)(B *b), B * b)
{
int x = 0;
clock_t t = clock();
for(int i = 0; i < 100000; i++)
{
x += f(b);
}
t = clock() - t;
std::cout << "x = " << x << std::endl;
std::cout << name << ": " << std::setprecision(6) << static_cast<double>(t) / CLOCKS_PER_SEC << std::endl;
}
#define TIME_IT(f, b) do { timeIt(#b, f, &b); } while(0)
int main()
{
A a;
V v;
V2 v2;
TIME_IT(func, a);
TIME_IT(func, v2);
TIME_IT(func, v);
system( "pause" );
}