Adam Matan
Adam Matan

Reputation: 136381

Are variable definitions that are used once optimized?

Consider the following method:

private static long maskAndNegate(long l) {
    int numberOfLeadingZeros = Long.numberOfLeadingZeros(l)
    long mask = CustomBitSet.masks[numberOfLeadingZeros];
    long result = (~l) & mask;
    return result;
}

The method can be abbreviated to:

private static long maskAndNegate(long l) {
    return (~l) & CustomBitSet.masks[Long.numberOfLeadingZeros(l)];
}

Are these two representations equal in actual run time? In other words, does the Java compiler optimize away the unnecessary definition of extra variables, that I've placed for readability and debugging?

Upvotes: 7

Views: 361

Answers (2)

Narendra Pathai
Narendra Pathai

Reputation: 41975

The code is not significantly large enough to be optimized for starters. And in the second way you are just saving the memory used for storing references to numberOfLeadingZeros and all.

But when you will use this code significantly enough on runtime such as 10000 times at least, then JIT will identify it as HOT code and then optimize it with neat tricks such as Method Inlining and similar sorts.

But in your case preferable option is first one as it is more readable.

You should not compromise Readability for small optimizations.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502536

The Java compiler itself hardly does any optimization. It's the JIT that does almost everything.

Local variables themselves are somewhat irrelevant to optimization though - a multi-operator expression still needs the various operands logically to go on the stack, just in unnamed "slots". You may well find that the generated bytecode for your two implementations if very similar, just without the names in the second case.

More importantly, any performance benefit that might occur very occasionally from reducing the number of local variables you use is almost certainly going to be insignificant. The readability benefit of the first method is much more likely to be significant. As always, avoid micro-optimizing without first having evidence that the place you're trying to optimize is a bottleneck, and then only allow optimizations which have proved their worth.

(By the time you've proved you need to optimize a particular method, you'll already have the tools to test any potential optimization, so you won't need to guess.)

Upvotes: 11

Related Questions