C++ arguments

Started by
9 comments, last by All8Up 12 years, 10 months ago
Typically const on primitive types will not have a performance impact. Const on reference/pointer types rarely has a performance impact, because C++'s aliasing problem effectively defeats most possible optimisations. Const is mainly a correctness issue. I've only seen const change the outcome of generated code significantly a few times.

The most flexible solution is to do both. E.g:

void setVertex(int x, int y, int z);

inline void setVertex(const Vertex &v)
{
setVertex(v.x, v.y, v.z);
}

Any modern compiler should trivially inline such a function. If your compiler cannot or will not inline such a function you're probably going to have a nightmare getting any kind of performance from it. TBH I would consider even the above a premature optimisation, I'd just use the setVertex(const Vertex &) as the definitive function until profiling indicated this was causing problems (which I highly doubt it will).


Especially considering the following is shorter without passing the struct.
[/quote]
This isn't much longer:

for(int x = -1 ; x <= 1 ; x += 2) {
for(int y = -1 ; y <= 1 ; y += 2) {
for(int z = -1 ; z <= 1 ; z += 2) {
setVertex(Vertex(v.x + x, v.y + y, v.z + z));
}
}
}
Advertisement

Typically const on primitive types will not have a performance impact. Const on reference/pointer types rarely has a performance impact, because C++'s aliasing problem effectively defeats most possible optimisations. Const is mainly a correctness issue. I've only seen const change the outcome of generated code significantly a few times.


As mentioned, I tend to agree but when it "does" make a change to the generated code it can be a serious pain in the ass to track down the problem. As such, I find it best to just 'try" to be mostly const correct given that it is easier to prevent the problems up front. A very specific example of const correctness which shows up regularly:


class xxx
{
xxx operator +( xxx& rhs );
};

Will typically not allow the compiler to apply the return value optimizations. This causes an invisible temp which based on construction/destruction cost can have an extremely negative impact on performance. Simply changing the above as follows gets rid of the temp.



class xxx
{
const xxx operator +( const xxx& rhs ) const;
};

Again, this is not an absolute given that you will or won't get the optimization in either case, it is just a very common issue I've seen over and over with various compilers. Of course it is actually better to use a friend operator for most compilers because the pinhole optimizers seem to correctly optimize them in more cases.

This topic is closed to new replies.

Advertisement