javac++compiler-optimization

Will one-time usages of local variables be optimized at compile time?


double calcTaxAmount() {
    double price = getA() * getB() + getC();
    double taxRate = getD() + getE();
    return price * taxRate;
}

The function above calculates the amount of tax payment.

The price and the rate are calculated by calling some other functions.

I introduced two local variables price and taxRate to just improve code readability, so both will be used only once. Will those kinds of "one-time" local variables be substituted and inlined at compile time with most modern compilers?


Solution

  • Obviously, it depends on the compiler. Quite a few compilers are actually brain-dead when it comes to optimization, because they are dealing with dynamic languages which are complex enough that most optimizations are invalid and many others are only safe if very restrictive conditions are met (for instance, any function call could have nearly any effect). For instance, all Python implementations feature a compiler, but most of them only do very few peephole optimizations, which may not be sufficient to eliminate all overhead.

    That said, if you're talking about statically typed languages (which your example hints at), then usually yes. Liveness analysis can detect the equivalence (you still need a storage location for, but the lifetime is the same), and any reasonably register allocator can avoid spilling the values needlessly.

    That said, this is a really bad focus for optimization. If you actually want to make stuff faster, look at the final code and profile with realistic scenarios. And if you're going to micro-optimize, apply some common sense. Even assuming this function is a hotspot, the actual computation and getting the values may easily take 100x more time. A non-inlined function call takes pretty long compared to a stack store, and a cache miss is also pretty cost at this level.