Are variable definitions that are used once optimized?

前端 未结 2 1601
温柔的废话
温柔的废话 2021-01-18 03:36

Consider the following method:

private static long maskAndNegate(long l) {
    int numberOfLeadingZeros = Long.numberOfLeadingZeros(l)
    long mask = Cust         


        
相关标签:
2条回答
  • 2021-01-18 03:44

    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.

    0 讨论(0)
  • 2021-01-18 04:09

    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.)

    0 讨论(0)
提交回复
热议问题