bun9
bun9

Reputation: 201

Could moving a const bool flag to the constructor cause better compiler optimization?

class DataProcessor {
   ProcessedData Process(const Data& data, bool do_something_special = true);
};

Suppose in every instance of DataProcessor, the do_something_special flag supplied is always the same (i.e. we only pass in false on special occasions through separate special instances). Would it be more optimal from a performance perspective to move the flag to the constructor and save it in a const bool member field?

Let's ignore which is the better API, I'm only interested in whether a compiler can make use of a const bool given in the ctor better than on a per-invocation basis. It's not constexpr so the compiler can't know whether it's true or false.

Upvotes: 0

Views: 71

Answers (1)

maxy
maxy

Reputation: 5467

Look at it like this: const is basically saying "I will not assign to this again". (Not "I know the value".)

During optimization, the compiler will look at dependencies between variable assignment, reorder things, unroll loops, move variables that don't change out of the loop, and possibly inline entire method calls. You can expect it to figure out whether you're assigning to the bool, const or not.

You'd have to construct a case where this analysis would conclude that your bool member could have been modified. (Probably via a non-const method call that the compiler didn't resolve, e.g. because it's virtual.) If so, the result would be an extra load from memory, usually no big deal.

The optimization you're probably after is to generate code that has the whole const bool compiled out, replaced with the actual value. But const doesn't help with that. Inlining can do that, or templates. Inlining may be more likely if your bool is an argument, rather than a class member (memory access). (Just a theory. Check the compiler's output to see if it already does inlining.)

Upvotes: 2

Related Questions