Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 712
Oliver Avatar asked Oct 25 '13 08:10

Oliver


People also ask

Do static methods take less memory?

Yes, static data will in a sense save memory since there's only a single copy of it. Of course, whether or not data should be static is more a function of the meaning or use of the data, not memory savings.

Do static classes take up memory?

Static data and static methods do not take up memory in individual instances.

Why You Should Avoid static classes?

Static classes have several limitations compared to non-static ones: A static class cannot be inherited from another class. A static class cannot be a base class for another static or non-static class. Static classes do not support virtual methods.

Is a static method faster in Java?

As expected, virtual method calls are the slowest, non-virtual method calls are faster, and static method calls are even faster.


2 Answers

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 (i.e. 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.)

like image 163
Jon Skeet Avatar answered Sep 20 '22 18:09

Jon Skeet


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.

like image 41
Szymon Avatar answered Sep 18 '22 18:09

Szymon