Effective consequences of & p [0] versus p.get () in boost :: scoped_array

The topic as a whole says it all. Basically in a situation like this:

boost::scoped_array<int> p(new int[10]);

      

Is there a noticeable performance difference between: &p[0]

and p.get()

?

I ask because I prefer the former, it has a more natural pointer like syntax. This effectively makes it so that you can replace p with your own pointer or array and don't have to change anything.

I'm guessing since get is one " return ptr;

" liner that the compiler will embed in this, and I hope it is smart enough to embed operator[]

in such a way that it cannot dereference and then link immediately.

Somebody knows?

+1


source to share


3 answers


OK, I did some basic tests as suggested by Martin York.

It seems that g ++ (4.3.2) is actually pretty good. At both optimization levels -O2 and -O3, it outputs a slightly different but functionally equivalent assembly for &p[0]

and p.get()

.

In -O, as expected, it took the path of least difficulty and issues a challenge operator[]

. It should be noted that the version &p[0]

causes g ++ to generate a copy of the body operator[]

, but it is never used, so there is a little code markup if you never use operator[]

otherwise:



The tested code was like this (with #if

and 0 and 1):

#include <boost/scoped_array.hpp>
#include <cstdio>

int main() {
    boost::scoped_array<int> p(new int[10]);
#if 1
    printf("%p\n", &p[0]);
#else
    printf("%p\n", p.get());
#endif
}

      

+1


source


The only way to know is to measure it!

But if you have a source of boost: scoped_array, you can step through the code and see what it does. I'm sure it's pretty similar.



T * scoped_array::get() const // never throws
{
    return ptr;
}

T & scoped_array::operator[](std::ptrdiff_t i) const // never throws
{
    BOOST_ASSERT(ptr != 0);
    BOOST_ASSERT(i >= 0);
    return ptr[i];
}

      

Write two versions of the code (one uses get () the other uses the [] operator). Compile the assembly with optimizations enabled. See if your compiler is actually optimizing the ptr + 0 command.

+2


source


Is this a question you are asking for academic interest only, or is it for some current code that you are writing?

In general, people recommend that code clarity be more important than speed, so if you are not sure if this will matter, you should choose whichever is more understandable and consistent with your code base. FWIW, I personally think get () is clearer.

0


source







All Articles