Re: std::vector slow?
On 8 Nov., 10:14, David Klein <dkle...@gmail.com> wrote:
I wrote a simple template class Vec and when I compile with
optimization under Visual Studio 2005, std::vector takes 56% more
time. I would have thought that std::vector is much more optimized
than anything I could roll myself. Am I mis-using std::vector somehow?
Or is it really that inefficient?
The comparable std::vector implementation is typically as
fast as a user-written version can be (or better). There are
some differences in your implementation:
1) Your hand-written Vec class violates the basic rule of three
and this has the effect (in your example) that it does not have
correct copy-semantic. Since your are neither copy-assigning
nor copy-constructing in your example, this does not influence
the example code, but has long-term effects (I just want to
mention as for completeness)
2) The Vec class has different initialization behaviour than
std::vector, because it does not value-initialize it's elements
(because it directly uses the array form of new in contrast
to std::vector), while std::vector consistently ensures
value-initialization of all elements. This has of-course direct
influence on the out-come of your test. To be fair, you would
have at least something like std::copy(mPtr, mPtr + mNElem)
for data types with trivial default c'tor (which are all in your
example code). Some further comments follow in between
your code lines.
3) One further comment regarding your test conditions see
at the end
template <class T> class Vec
{
public:
Vec(int size) : mNElem(0), mPtr(NULL)
{
if (size < 0) throw "Size < 0\n";
if (size > 0)
{
mPtr = new T [size];
if (mPtr == NULL)throw "Vec allocation failed\n";
This cannot happen on any conforming compiler, because
only the std::nothrow_t variant of new[] is allowed to return
a NULL pointer (if memory is not sufficient)
~Vec(void)
{
if (mPtr) delete [] mPtr;
The NULL check is redundant, because delete[] is supposed
to perform this NULL check on its own.
mPtr = NULL;
mNElem = 0;
This assignments are essentially effectless, because the
object is going to be destructed.
T &operator[](const int i) const { return mPtr[i];}
This is a rather unusual operator[] overload, which allows
modification of an immutable container.
Here are my compiler options:
/O2 /GL /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_UNICODE" /D
"UNICODE" /FD /EHsc /MD /Fo"Release\\" /Fd"Release\vc80.pdb" /W3 /
nologo /c /Wp64 /Zi /TP /errorReport:prompt
I see that you do not explicitely disable _SECURE_SCL, this means
that every index-based access (also: iterator-based) via operator[]
will be checked for validity. You should disable this validation to
make
your tests comparable.
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]