曾经优化过的变量定义是否被优化? [英] Are variable definitions that are used once optimized?

查看:97
本文介绍了曾经优化过的变量定义是否被优化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下方法:

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

该方法可以缩写为:

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

这两种表示在实际运行时间中是否相等?换句话说,Java编译器是否优化了我为可读性和调试而放置的多余变量的不必要定义?

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?

推荐答案

Java编译器本身几乎不做任何优化.几乎所有事情都是JIT.

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

这篇关于曾经优化过的变量定义是否被优化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆