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
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.
Static data and static methods do not take up memory in individual instances.
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.
As expected, virtual method calls are the slowest, non-virtual method calls are faster, and static method calls are even faster.
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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With