Question

I have a code

void Foo()
{
    auto index = currentIndex();
    if (index.isValid())
        index.doSomething();
}

another option

void Foo()
{
    if (currentIndex().isValid())
        currentIndex().doSomething();
}

The second one is more readable for me. But how is its performance? Is currentIndex() computed twice in current popular compiler? If currentIndex() is a large function which takes some CPU time, does the compiler will optimize the second one as the first one?

Was it helpful?

Solution

The first will likely have better performance and IMO is more readable because if you just call currentIndex() by itself you have no information on it. If you assign it to a variable you have it for future use.

A compiler would have no chance of optimizing the call out, for many reasons

  1. the first call could have changed the result of the next call
  2. The having 2 calls of the function can change the state of your program
  3. Probably a whole bunch of other reasons I can't think of

So in conclusion there is no reason why you wouldn't use the first version, I can assure that most people would also find that version more readable. Assigning data to a name is one of the corner-stones of modern programming so if it is more readable to you when the data has no name you may want to get used to variables having names

Another note, to make it more readable don't use auto, that is better saved for template programming where the type can be a pain to figure out on your own.

OTHER TIPS

To me, the first option leaves no questions in performance, which is what I would prefer.

That being said, it all depends on context, usage, and the cost of currentIndex(). If currentIndex() is a trivial getter, and Foo() isn't called in some heavy loop, then there is little difference, if any.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top