Reputation: 16870
I have a class cnVector
that represents a point in 3 dimensional space.
Its operators + - * / are used intensively.
Their implementation is very short:
cnVector cnVector::operator + (const cnVector& v) const {
return cnVector(
x + v.x,
y + v.y,
z + v.z );
}
My question is, because this function is very short, should I inline it although its intensive use? or would it generate too much code when using it that much?
Upvotes: 5
Views: 219
Reputation: 545628
Apply inline
to all functions that you define in your header on namespace scope to avoid breaking the One Definition Rule. This, by the way, is completely unrelated to inlining, despite the keyword name. (Or put them inside an anonymous namespace.)
inline
also gives a hint to the compiler to inline calls to said function, but as the comments have pointed out the compiler is quite capable of figuring that out by itself so the keyword isn’t really needed for that.
Upvotes: 3
Reputation: 5722
If in doubt, compile it with and without inline and compare execution speed and size. The compiler usually offers a switch for profiling as mentionend above to see what the function call costs, measured in time,
Upvotes: 1
Reputation: 39960
The compiler is perfectly capable of making a decision as to whether to inline a function or not depending on the chosen optimization profile.
You should inline a function if the compiler doesn't, and profiling with a realistic data set shows you're spending a significant amount of time in the function, the algorithm using said function is an efficient one, and if inlining it shows a speed improvement in a benchmark with said data set.
Upvotes: 2
Reputation: 9435
Remember that using inline is never a guarantee, it just gives a hint to the compiler. I doubt inlining will actually increase executable size a lot, the function is very small in itself.
Calling the function is almost the same size as the function itself.
Upvotes: 5
Reputation: 10917
Yes you probably should. The good use case for the inline keyword in c++ is: small functions, heavily used.
See also http://msdn.microsoft.com/en-us/library/1w2887zk%28v=vs.80%29.aspx
Upvotes: 5