Search code examples
flutterperformancedartclassstatic

Flutter static usage and performance?


at my company, my teammate said that"in Flutter, static usage is very harmful for memory. You shouldn't use static variables too much."

After that, I have searched the internet, but I couldn't find satisfaction answer. So, I just wonder that if I use static value like at the below code lines, will it increase memory usage or reduce performance? Many thanks.

class {
static final String name="asd";
static final String surname="ajskandkanjsd";
static final Int age=123;
static final isStudent=false;
static final String email="[email protected]";
static final Int password=1231234;
}

Solution

  • An object referenced by a static (or equivalently, global) variable will live for the lifetime of your program. The garbage collector will never free it until either your program terminates or until you explicitly remove that reference (such as by reassigning your static variable to refer to a different object).

    Since static objects typically are long-lived, they could increase memory usage. However, that's typically not a problem because there's a fixed (and usually not very large) number of static variables in your program. They're typically not going to consume an unbounded amount of memory.

    It could be a problem if you have a static variable that refers (whether directly or indirectly) to some collection object that could grow dynamically without constraint (a cache with a bad policy is another name for a memory leak), but that'd be something to watch out for for any long-lived collection and wouldn't be specific to static/global variables.