22

How does C#, or other languages for that matter, handle memory allocation (and memory de-allocation) between these two scenarios:

1.) A method on a static class is invoked.

public Program {
    Foo foo = Loader.load();
}

public static Loader {
    public static Foo load() {
        return new Foo();
    }
}

2.) A method is invoked on an instance, which then falls out of scope.

public Program {
    Foo foo = new Loader().load();
}

public Loader {
    public Foo load() {
        return new Foo();
    }
}

I suppose the static class is loaded, and remains, in memory; whereas the class instance succumbs to garbage collection at C#'s leisure. Are there any pros or cons to these two paradigms? Is there ever a time when you have a class that never needs to be instantiated (i.e. some sort of resource loader or factory), but you use the second methodology anyway to take advantage of garbage collection?

The important part of my question is whether or not the first paradigm, while being conceptually correct in some circumstances, may suffer from holding on to memory unnecessarily.

6
  • 3
    The 2nd example seems incorrect to me. Calling a static method requires one it to prefix with class name. e.g. Loader.Load() & not new Loader().Load() Commented Feb 27, 2010 at 17:55
  • You're right, Shah - you don't need an instance to call a static method. That's kinda the point :) Commented Feb 27, 2010 at 18:14
  • ah, you guys are right, thanks, I've reworded it to get at the meat of the question I was attempting to ask. Commented Feb 27, 2010 at 18:30
  • 1
    i think what he means, are the overheads of having a static class bigger then creating a new instance and calling a method of that instance, and then letting the GC collect it. Commented Feb 27, 2010 at 18:32
  • Brevity is the soul of wit, thanks for perfectly summarizing my question in 5 words, haha. Commented Feb 27, 2010 at 18:58

4 Answers 4

9

Your second example doesn't work, so let's explore the real options:

1.) A method on a static class is invoked.

public Program {
   Foo foo = Loader.Load();
}

public static Loader {
   public static Foo Load() {
      return new Foo();
   }
}

2.) A static method in a non-static class is invoked.

public Program {
   Foo foo = Loader.Load();
}

public Loader {
   public static Foo Load() {
      return new Foo();
   }
}

3.) An instance method is invoked on an instance

public Program {
   Foo foo = new Loader().Load();
}

public Loader {
   public Foo Load() {
      return new Foo();
   }
}

The two first are the same. Calling a static method is the same regardless if the class is static or not.

The third option will create an instance of the class on the heap. As the class has no data members, it will only be something like 16 bytes. It will be garbage collected eventually, but due to the small size it doesn't matter much when that happens.

Calling an instance method is also slightly different from a static method. A reference to the class instance is sent along, that you can access through the this keyword. It makes little difference in this case as there is no real data in the object to access.

Sign up to request clarification or add additional context in comments.

4 Comments

Does the memory footprint of a C# program change when an instance of an object is garbage collected (besides the instance field data, obviously), is there ever any unloading of the Type information that ever takes place? To put it colloquially, will C# ever perform any optimization like "Oh, none of these classes currently have instances, I don't need them any more, I'll unload the raw Type data from the program and save myself some memory"?
@jtb: No, to my knowledge .NET will not unload an assembly that was once loaded.
@jtb GC will only free memory taken by your class only if it has no references/handles etc and only when OS memory resources are scarce.
@TomasVoracek: Yes, that is the memory taken by instances of the class. The class itself (code + statics) is not collected.
1

The second form creates a temporary Loader object (which is very cheap). You will always have to load the Loader class, no matter which approach you choose.

There is very little performance (memory saving) to gain here. You would normally choose for a static member in a static class if there is no 'state' needed outside the methods local vars.

2 Comments

@Shah It will compile. note 2nd example is not calling a static method! It is calling a normal public method within an instance which is then garbage collected as it is never refrenced again.
yeah, people are confused because my original post had the method in the second example marked as static, I edited it.
1

A static method, field, property, or event is callable on a class even when no instance of the class has been created.

http://msdn.microsoft.com/en-us/library/79b3xss3(VS.80).aspx

So in that sense your static methods behaves just as it would if you used it from within a class instance: it is scoped to the type.

2 Comments

yeah, sry, my example suffers from being poorly written to illustrate my question. I don't know if this is proper SO etiquette, because you are correct, but I'm going to have to rephrase my question slightly in order to ask the question I really wanted to.
Given that a static member is scoped to the type, I don't think the memory usage is going to change just because you call it within an instance of that type.
0

I cannot find any sources for this, but from my knowledge of programming, when you refernce a class(non static), it's structure is loaded into memory

Creating an instance of a class just to call a method, would waste a lot of processing power(due to creating an instance, assigning it memory, and the garbage collecting).

Instead of keeping the definition, and then on top of it, an instance. Why not just keep the definition(static).

As long as you don't store any data in static variables, your static method should take up the same amount of memory as your non static method definition. But using a static method, only the method will be kept in memory and be ready to be called whenever you need without creating instances. Where as, if the method is non static, it will need to be instantiated(using up memory and processing power) and the garbage collected(freeing memory and using up cpu) therefore it is definitely better using a static member. Thats what they are there for.

1 Comment

When a static class is first referenced, my understanding is that C# runs the static initializer, loads static fields into memory, and loads the Type data (class structure) into memory, keeping it there for the duration of program runtime. When an instance of a class is created, the constructor is processed, memory is allocated for instance fields and Type data is loaded into memory (if it's not there already). However, when an instance of a class leaves scope, it's data is eventually bequeathed to the ether, but is the Type data ever released?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.