For example I have these two classes:
First
public class Example
{
public Example()
{
}
public int ReturnSomething
{
return 1;
}
}
Second
public class Example
{
public Example()
{
}
public static int ReturnSomething
{
return 1;
}
}
I want to use the ReturnSomething
method, which of the two classes allocated less/more memory? When I use
int x = Example.ReturnSomething;
or when I use
Example object = new Example();
int x = object.ReturnSomething();
2
If you don’t use the object inside a method (i.e. you don’t have this.
), then make it static. In .NET Framework, for example, in order to be Code analysis compliant, you have to use static in this case (see rule CA1822: Mark members as static).
Also consider OOP in order for your code to be readable. Is the method inherent to the instance of the object? Is it more appropriate for class only, but not the instance? Is the method appropriate here in the first place?
Note: you’re expected to write code for humans, not computers. Unless you work on embedded hardware, write your code with the consideration of readability, not memory consumption. If you’re instead in a case where every byte of memory counts, profile the application to determine which of multiple ways of solving the problem matches the non-functional requirements related to memory consumption.
2
MainMa provided a great answer to your unspoken question (“Which option should I choose”), but, for completeness, I thought I’d answer your explicit question:
I want to use the ReturnSomething method, which of the two classes allocated less/more memory?
Your second option allocates a tiny bit more memory. 12 bytes, to be precise, if you are running an x86 application with .NET 4. However, your object will be garbage collected as needed (unless you actively do something to prevent that), so this becomes irrelevant in the long run (even on very memory-constrained devices).
Unless you have a very good reason for it, this tiny amount should not influence your decision. There are very good reasons to choose the static option, but this is not one of them.