Does using final for variables in Java improve gar

2019-01-08 05:58发布

Today my colleagues and me have a discussion about the usage of the final keyword in Java to improve the garbage collection.

For example, if you write a method like:

public Double doCalc(final Double value)
{
   final Double maxWeight = 1000.0;
   final Double totalWeight = maxWeight * value;
   return totalWeight;  
}

Declaring the variables in the method final would help the garbage collection to clean up the memory from the unused variables in the method after the method exits.

Is this true?

14条回答
smile是对你的礼貌
2楼-- · 2019-01-08 06:26

Final variables cannot be changed after initial assignment (enforced by the compiler).

This does not change the behaviour of the garbage collection as such. Only thing is that these variables cannot be nulled when not being used any more (which may help the garbage collection in memory tight situations).

You should know that final allows the compiler to make assumptions about what to optimize. Inlining code and not including code known not to be reachable.

final boolean debug = false;

......

if (debug) {
  System.out.println("DEBUG INFO!");
}

The println will not be included in the byte code.

查看更多
We Are One
3楼-- · 2019-01-08 06:26

There seems to be a lot of answers that are wandering conjectures. The truth is, there is no final modifier for local variables at the bytecode level. The virtual machine will never know that your local variables were defined as final or not.

The answer to your question is an emphatic no.

查看更多
登录 后发表回答