Home > database >  Whats the scope of const and how to measure it?
Whats the scope of const and how to measure it?

Time:01-03

Lets say you have a class Bird that has a const constructor:

class Bird { 
  const Bird();      
  void fly() {}
}

You need to use it in a place but you have two options:

1.

const bird = Bird();
void doIt() {
  bird.fly();
}
void doIt2() {
  const bird = Bird();
  bird.fly();
}

Questions :)

  • Is there any difference between 1. and 2.? is 2.?

Im thinking that there are no difference in terms of performance but Im not really sure how to measure it

  • Whats the scope of const constructors?
  • How can I measure that?

CodePudding user response:

  • In the first example you have an instance variable. Instance variables are variables that are defined in the class, for which each instantiated object of that class has a separate copy or instance of the variables.
  • In the second example you have a local variable. After the calculate function executes, the local variables will no longer exist except of cases of closures.

By the way.

Use final for local variables that are not reassigned and var for those that are.

Use var for all local variables, even ones that aren’t reassigned. Never use final for locals. (Using final for fields and top-level variables is still encouraged, of course.)

https://dart.dev/guides/language/effective-dart/usage

CodePudding user response:

There is no difference in the value or the efficiency of accessing it.

The only difference is that in version 1, other code can refer to the bird variable, and in version 2, it's a local variable inside the function, and cannot be seen from the outside.

Just like any other variable, its scope is defined by where it's declared, not what its value is.

  • Related