2

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();
gnat
  • 21,442
  • 29
  • 112
  • 288
  • Another thing worth considering would be unit testing; static classes are [hard to mock](http://stackoverflow.com/questions/1823739/mocking-a-static-class) (although you may not need to mock a static method to unit test it, it would depend on your exact situation). – Daniel B May 29 '13 at 06:26
  • see also [Make methods that do not depend on instance fields, static?](http://programmers.stackexchange.com/q/215826/31260) – gnat Apr 11 '16 at 08:02

2 Answers2

7

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.

Arseni Mourzenko
  • 134,780
  • 31
  • 343
  • 513
3

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.

Heinzi
  • 9,646
  • 3
  • 46
  • 59