对不起,如果这是一个新手问题,但我找不到答案.这样做更好吗:
Sorry if this is a newbie question but I couldn't find an answer for this. Is it better to do this:
int result = number/number2;
return result;
或:
return number/number2;
我知道整数使用内存,所以我猜它会稍微降低性能?但另一方面,它使内容更清晰,尤其是当 int/string 是一个长计算时.
I know integers use memory so I'm guessing it will slightly decrease performance? But on the other hand it makes stuff clearer, especially when the int/string is a long calculation.
如果像我一样,您使用的 Kotlin 比 Java 还多,那么了解这一点也很重要IntelliJ 在 Kotlin 中也对此进行了检查:
if, like me, you've been using more Kotlin than Java, it'd also be relevant to know that IntelliJ also has an inspection for this in Kotlin:
变量只在后面的返回中使用,应该被内联
Variable used only in following return and should be inlined
此检查报告仅在下一个 return 语句中使用的局部变量或其他变量的精确副本.在这两种情况下,最好内联这样一个变量.
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 规则,称为 返回之前的不必要的本地,谈论这个.它说:
There is actually a SonarQube rule inherited from PMD called Unnecessary Local Before Return that talks about this. It says:
避免不必要地创建局部变量.
Avoid unnecessarily creating local variables.
此规则后来被 SSLR 规则替换不应声明变量然后立即返回或抛出,保持相同的位置:
This rule was later replaced by SSLR rule Variables should not be declared and then immediately returned or thrown, which maintains the same position:
声明一个变量只是为了立即返回或抛出它是一个错误练习.一些开发人员认为这种做法改进了代码可读性,因为它使他们能够明确地命名正在发生的事情回.但是,此变量是内部实现细节不会暴露给方法的调用者.方法名应该足以让来电者确切知道会发生什么返回.
Declaring a variable only to immediately return or throw it is a bad practice. Some developers argue that the practice improves code readability, because it enables them to explicitly name what is being returned. However, this variable is an internal implementation detail that is not exposed to the callers of the method. The method name should be sufficient for callers to know exactly what will be returned.
我完全同意.
IntelliJ(或至少是 Android Studio)也有针对这种情况的警告:
IntelliJ (or at least Android Studio) also has a warning for this situation:
变量只在后面的返回中使用,可以内联
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 很可能会内联变量,无论哪种方式,您最终都会得到相同的结果.
I don't think performance is something to worry about at all in this situation. That being said, as @Clashsoft mentioned in his comment, the JIT will most likely inline the variable and you'll end up with the same result either way.
这篇关于return 语句之前的局部变量,这有关系吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!