Home > OS >  Flutter static usage and performance?
Flutter static usage and performance?

Time:12-02

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;
}

CodePudding user response:

No, it does not affect memory and performance because the memory allocation for static variables happens only once in the class area at the time of class loading. if you do not make it static then every time when you create a new object of the class it takes new memory space. so it increases memory usage.

CodePudding user response:

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 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 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 at all be specific to static/global variables.

  • Related