Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

As per Joshua Bloch's book "Effective Java", Item 15 - Minimize mutability, using final keyword on private class fields in addition to immutability and thread-safe syncing could improve performance.

class Immutable {
    private final int readOnly;

    public Immutable(int readOnly) {
        this.readOnly = readOnly;
    }

    public int getReadOnly() {
        return readOnly;
    }
}

But sometimes, especially in Android code i see something like this:

class MyClass {
    private void myMethod() {
        final List<A> list = new ...;
        final B b = new B();
        ...  
    }
}

When final word applied to reference object. This means that the reference isn't mutable, but has it any influence on performance?

share|improve this question

closed as off topic by codesparkle, dreza, Brian Reichle, Stephen C, Jeff Vanzella Nov 27 '12 at 16:49

Questions on Code Review Stack Exchange are expected to relate to code review request within the scope defined by the community. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about reopening questions here.If this question can be reworded to fit the rules in the help center, please edit the question.

    
Welcome, Dmitriy. This is off-topic and should be migrated to Stack Overflow. I answered it anyway. –  codesparkle Nov 27 '12 at 7:38

1 Answer 1

up vote 3 down vote accepted

It has no measurable impact on performance. Even if a few milliseconds were wasted, it would not be significant. If you're worrying about performance at this level, you might as well program in assembly.

However, declaring local variables as final is often required in order to access them in an anonymous local class (aka closure), for instance in an action listener (frequently used in Android development):

final String playerName = "test"; // has to be final, compiler error otherwise
option = new JRadioButton(playerName, false);
option.addActionListener(new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent evt) {
        partner = playerName;
    }
});

The reason for this is the code the compiler generates for anonymous classes.


There are other reasons to declare local variables as final:

  • To reduce mutability of the code as a whole
  • To clarify intent ("I am not going to change this reference after assigning it")
  • To prevent accidental assignment
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.