java:为什么局部变量应该声明为final

发布于 2025-01-03 06:21:04 字数 643 浏览 2 评论 0原文

可能的重复:
声明方法是否有任何性能原因Java 中的最终参数?
为什么要标记局部变量Java 中方法参数为“final”?

我正在使用 PMD 来查看代码违规。

在 webService 方法中,我有下面的代码

public ServiceRequest getData()
{
Status status = new Status();
// code
}

PMD 建议我的是,这个局部变量状态可以声明为最终状态。

我的问题是,将其定为最终版本会带来任何性能改进,或者如果不是的话,代码可以获得什么好处?

Possible Duplicate:
Is there any performance reason to declare method parameters final in Java?
Why would one mark local variables and method parameters as “final” in Java?

I am using PMD to see the code violations.

Inside a webService Method, I have this below code

public ServiceRequest getData()
{
Status status = new Status();
// code
}

What PMD is suggesting me is that, this local variable status could be declared as final.

My question is, making it final would result in any performance improvements or if not what benefits the code could get?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

埖埖迣鎅 2025-01-10 06:21:04

摘自以下文章: http://www.javapractices.com/topic/ TopicAction.do?Id=23

  • 清楚地传达您的意图
  • ,允许编译器和虚拟机执行较小的优化,
  • 清楚地标记行为更简单的项目 - 最后说,“如果您正在寻找复杂性,您将找不到它 这里。”

这个问题也讨论了这一点: 可以过度使用最终伤害多于好处?

Taken from the following article: http://www.javapractices.com/topic/TopicAction.do?Id=23

  • clearly communicates your intent
  • allows the compiler and virtual machine to perform minor optimizations
  • clearly flags items which are simpler in behaviour - final says, "If you are looking for complexity, you won't find it here."

This is also discussed in this question: Can excessive use of final hurt more than do good?

つ低調成傷 2025-01-10 06:21:04

final 表示局部变量不会被改变。我的感觉是方法应该很短,您应该能够轻松理解它们,因此将变量设置为最终可能有点多余。

我更喜欢将字段设置为final,因为使整个类如此短,是一个严重的限制。此外,字段可能存在线程安全问题,而局部变量则不会。

final indicates the local variable won't be changed. My feeling is that methods should be so short you should be able to easily understand them and so making the variable final may be a bit redundant.

I prefer to make fields final because making the whole class so short, is a serious limitation. Also fields can have thread safety issues which local variables do not.

乙白 2025-01-10 06:21:04

我不知道将状态设置为最终状态会带来什么性能优势,但 PMD 建议您这样做,因为您可能永远不会在状态首次初始化后对其进行写入。

因此,通过将其设为最终版本,您所获得的只是您的代码更不容易出错 - 如果您将其声明为最终版本,则不能错误地覆盖它......

I dont know about performance-benefits by making status final, but PMD is suggesting you this, because probably you are never writing on status after its first initialization.

So what you gain by making it final is just that your code is less error-prone - if you declare it final, you cant overwrite it by mistake...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文