Drew
Drew

Reputation: 421

Static Methods Memory Consumption

I have the following class with the following methods:

public class Foo
{
   public string A {get;set;}

   public static Foo New(string a)
   {
      Foo newFoo = new Foo();
      newFoo.A = a;
      return newFoo;
   }
 }

 public class Bar
 {
   public void SomeMethod()
   {
       ...
       Foo anotherFoo = Foo.New("a");
       ....
   }
 }

If the Bar class creates Foo during a process using the above code, will Foo ever go out scope and get garbage collected or will Foo (because it is using a static method) continue to have a reference to variable newFoo and therefore anotherFoo will never go out of scope?

Upvotes: 3

Views: 5557

Answers (3)

VdesmedT
VdesmedT

Reputation: 9113

Classes never "goes out of scope". Instance (references) do. As for the newFoo reference, it goes out of scope when the method New ends as will anotherFoo when the SomeMethod method ends.

The fact that the method is static does not changes anything, in fact, you coudl even have a static variable in Foo that it wouldn't change anything because static variable are create on a separate heap called "high frequency heap" where GC obviously never collect anything.

Upvotes: 1

Tejs
Tejs

Reputation: 41246

a leaves scope as soon as Foo.New() completes. The reference to newFoo is returned, and then newFoo goes out of scope. SomeMethod still has a reference to that instance via the anotherFoo reference, so that reference is not available for garbage collection until SomeMethod completes, unless that reference is saved.

Upvotes: 4

Adam Houldsworth
Adam Houldsworth

Reputation: 64487

The presence of static methods doesn't impact an object's eligibility for GC, only references to that object do. In your case anotherFoo will be the only reference. The reference newFoo goes out of scope when the method returns, popping off the stack.

Local variables inside static methods are not themselves "static", when the method returns, those locals will be popped from the execution stack the same as non static methods.

The underlying object behind anotherFoo will become eligible for GC when SomeMethod returns (well, the compiler is more aggressive and can make it GC-able when anotherFoo is no longer used in the code).

Upvotes: 6

Related Questions