简体   繁体   中英

Android static class vs non-static class memory performance

I've created a class which was static first, this class does not persist state (does not keep context or any variables) is just a list of functions. But the class is not very used in the app so I decided to make class instantiable.

Why?

Because I think an instantiable class would use less memory as it is not available during the whole app life cycle.

Is this right?

A static class uses more memory than a non-static class?

Thank you

I think you've misunderstood how classes work. Any kind of class is "available" throughout the lifetime of the app. Memory used for the class itself (the methods etc) is very different to memory used by instances . Unless you actually create an instance of the class, it's irrelevant. And even static classes can be instantiated - it's just that they don't maintain an implicit reference to an instance of the enclosing class.

If your class doesn't actually require an implicit reference (ie it doesn't use it) then make it a static nested class - or pull it out as a top-level class anyway. (Nested classes can be a pain sometimes - the rules around top-level classes are simpler.)

A static class as such doesn't use more memory than a non static one. All classes are always available in an application - you can always use a static class or create an instance of a non static one.

If you have only methods in your class (which are of a helper method types) a static class is more convenient to use (no need to create an instance) and won't affect your memory usage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM