5
for (var foo in bar) print(foo);
for (final foo in bar) print(foo);

Is there any difference in performance between these two? Or is the only difference "avoiding accidental reassignments"?

Edit: prefer_final_locals mentions compiler performing optimizations when final is used. Will it apply here? dart2js output matches for the 2 snippets above. Not sure about dart2native.

2
  • 3
    It's a good programming practice to use 'final' if the variable is not going to be reassigned. It avoids errors due to wrong assignments.
    – Sabareesh
    Jul 16, 2020 at 10:35
  • 4
    I rather doubt that using final instead of var matters for optimization for local variables. Even if it mattered, the compiler should be able to easily determine itself whether a local variable is reassigned or not. Additional skepticism: github.com/dart-lang/linter/issues/2103
    – jamesdlin
    Jul 17, 2020 at 2:25

2 Answers 2

5

The only difference is that you can reassign the foo value if you use var.

for (var foo in bar) {
  foo = foo + 5;
  print(foo);
}

doing so using final would not work

for (final foo in bar) {
  foo = foo + 5; //Error: The variable foo can be set only once
  print(foo);
}

2
  • 2
    prefer_final_locals mentions that compiler can do optimizations when final is used. Will it apply in this case? Jul 17, 2020 at 1:55
  • 5
    If the compiler cannot recognize that a variable is not reassigned, and optimize it as a final variable when it isn't, the compiler should feel bad. I wouldn't worry about that.
    – lrn
    Jul 17, 2020 at 8:20
-5

From Dart Style Guide:

DON'T use final for local variables.

var is shorter, and final does not change the meaning of the code.

https://dart-lang.github.io/linter/lints/unnecessary_final.html

3
  • 1
    That's just one option; it's not the standard. In fact that page links to prefer_final_locals which enforces the opposite. Apr 15, 2021 at 8:22
  • 1
    So, as said there, "prefer_final_locals (Incompatible with: unnecessary_final)" and "unnecessary_final (Incompatible with: prefer_final_locals.)". It's only a matter of taste, but again, var is shorter and the default on Dart documentation examples: dart.dev/guides/language/effective-dart/usage
    – Fred
    Apr 16, 2021 at 14:29
  • 2
    Later on that same page, it says that both are acceptable, and the only universal rule is to be consistent: dart.dev/guides/language/effective-dart/… Apr 17, 2021 at 1:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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