做javac或Hotspot自动添加'final'作为不变量变量的优化? [英] Do javac or Hotspot automatically add 'final' as an optimisation of invariant variables?

查看:124
本文介绍了做javac或Hotspot自动添加'final'作为不变量变量的优化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一致似乎是将成员变量标记为final的性能优势,因为它们不需要从主内存中重新加载。我的问题是,做javac或热点自动做这个对我来说,当显而易见的变量不能改变。例如将javac在这个类下面的'x'final在下面...

The consensus seems to be that there is a performance benefit to marking member variables as final because they never need reloading from main memory. My question is, do javac or Hotspot automatically do this for me when it's obvious the variable cannot change. eg will javac make 'x' final in this class below...

public class MyClass {
   private String x;

   MyClass(String x) {
      this.x = x;
   }

   public String getX() {
      return x;
   }
}

在第二点上,任何人都产生了经验证据标记成员作为最终使代码运行更快?

On a secondary point, has anyone produced empirical evidence that marking members as final makes code run faster? Any benefit is surely negligible in any application making remote calls or database lookups?

推荐答案

像许多性能增强一样,它通常是一个更好地问;什么是更容易理解和理由?例如如果一个字段是final,我知道它不会在任何地方改变。这通常导致更优化的代码,但更重要的是它应该是更可维护的代码。 ;)

Like many performance "enhancements" it is usually a better to ask; What is easier to understand and reason about? e.g. if a field is final I know it won't be changed anywhere. This is often leads to more optimial code, but more importantly it should be more maintainable code. ;)

当然,我做任何可以是final的字段。我个人更喜欢 final 是默认行为,你必须使用 var 这样的关键字使其可变。

Certainly, I make any field which can be final as final. Personally I would have preferred that final be the default behaviour and you had to use a keyword like var to make it mutable.

这篇关于做javac或Hotspot自动添加'final'作为不变量变量的优化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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