Dart final keyword performance impact

Viewed 264

I am aware that once assigned a value, a final variable's value cannot be changed. Does the keyword final have a positive performance impact compared to a not-final variable?

1 Answers

For local variables, there is no advantage. Any competent compiler can detect whether a local variable is assigned to, whether it's declared final or not.

For instance variables, it's harder to detect whether there is a subclass overriding the variable, or some other implementation of the interface. That means that even if the variable is final, the compiler can rarely trust that for anything. A compiler with access to the whole program might detect that there is no assignment anywhere. It makes a difference for your API though.

For static and top-level variables there might be a slight advantage in making the variable final. It means that local analysis can know that the value won't change, even without seeing the entire program.

All in all, anything but local variables, you should make unchanging variables final because it's good modelling, not because you worry about performance. For local variables, it doesn't matter.

Related