-1

What is the more efficient way to use inline codes in c++.

Should i use it for operators surcharge ?

inline const Composant & Composant::operator=(const Composant &c)
{
    if (this != &c)
{
    free(_description);
    _description = strdup(c.getDescription());
}

In order to have the best performance ... I do not want to use it TOO much.

Thank you

Mxsky
  • 749
  • 9
  • 27

1 Answers1

1

I'm ignoring "style" as a reason for inlining/not inlining code. This is of course in reality a very important part.

Your example of operator= is a very good one that I would inline. It adds only a little bit of code:

A compare between this and address of c, a branch, a call to free and a call to strdup (and storing the return value).

However, if your operator= becomes 10-15 lines, more calls to free or delete, etc, then perhaps making non-inline is a good idea.

As with a lot of things, it's a judgement (or to give it a fancy name "engineering decision", but most of the time those are simply "I know this will work OK"), and to REALLY know which is better you need to measure and profile your code to understand where it spends its time and "how do I make that less".

The most important functions are those that are used inside loops, in particular those that have a high number of iterations. Most programs have between one or half a dozen such loops that are "where most of the time is spent". Optimising other code is pretty meaningless, since it may be executed a dozen times in the overall execution of your program, which executes the main loop a million times. Making the "a dozen times" code run 12 clock-cycles faster per call isn't going to matter. Making the inner part of your million times loop 12 clock-cycles faster per loop may make a difference, because now it's 12 million cycles faster. And if you have thirty function calls in your central loop, and you make each of those on average 12 cycles faster, now we're talking about hundreds of millions of cycles, so now we're in the tenths of seconds on a modern processor.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227