gpt4 book ai didi

java - return 语句之前的局部变量,这有关系吗?

转载 作者:IT老高 更新时间:2023-10-28 20:51:50 25 4
gpt4 key购买 nike

对不起,如果这是一个新手问题,但我找不到答案。这样做更好吗:

int result = number/number2;
return result;

或:

return number/number2;

我知道整数使用内存,所以我猜它会稍微降低性能?但另一方面,它使内容更清晰,尤其是当 int/string 是一个长计算时。

最佳答案

编辑:如果像我一样,您使用的 Kotlin 比 Java 还多,知道 IntelliJ 在 Kotlin 中也对此进行检查也很重要:

Variable used only in following return and should be inlined

This inspection reports local variables either used only in the very next return statement or exact copies of other variables. In both cases it's better to inline such a variable.


实际上有一个从 PMD 继承的 SonarQube 规则,称为 Unnecessary Local Before Return 谈到这个。它说:

Avoid unnecessarily creating local variables.

这条规则是later replaced通过 SSLR 规则 Variables should not be declared and then immediately returned or thrown ,它保持相同的位置:

Declaring a variable only to immediately return or throw it is a badpractice. Some developers argue that the practice improves codereadability, because it enables them to explicitly name what is beingreturned. However, this variable is an internal implementation detailthat is not exposed to the callers of the method. The method nameshould be sufficient for callers to know exactly what will bereturned.

我完全同意。

IntelliJ(或至少是 Android Studio)也有针对这种情况的警告:

Variable used only in following return and can be inlined

This inspection reports local variables either used only in the very next return or exact copies of other variables. In both cases it's better to inline such a variable.


我认为在这种情况下根本不需要担心性能问题。话虽如此,正如@Clashsoft 在他的评论中提到的那样,JIT 很可能会内联变量,无论哪种方式,您最终都会得到相同的结果。

关于java - return 语句之前的局部变量,这有关系吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31733811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com