返回语句之前的局部变量,是否重要? [英] Local variables before return statements, does it matter?

查看:515
本文介绍了返回语句之前的局部变量,是否重要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

实际上有一个继承自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规则 后来替换 =https://dev.eclipse.org/sonar/coding_rules#rule_key=squid%3AS1488%7Cs=createdAt%7Casc=false =nofollow noreferrer>不应声明变量,然后立即返回或抛出变量 ,保持相同的位置:

This rule was later replaced by SSLR rule Variables should not be declared and then immediately returned or thrown, which maintains the same position:


声明变量只是为了立即返回或抛出它是一个坏b $ b练习。一些开发人员认为这种做法提高了代码
的可读性,因为它使他们能够明确地命名返回的
。但是,此变量是一个内部实现细节
,不会向方法的调用者公开。 方法名称
应足以让来电者确切知道
返回的内容

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.

这篇关于返回语句之前的局部变量,是否重要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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