Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Methods Memory Consumption

Tags:

c#

memory

static

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?

like image 503
Drew Avatar asked Aug 02 '26 14:08

Drew


1 Answers

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).

like image 82
Adam Houldsworth Avatar answered Aug 04 '26 03:08

Adam Houldsworth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!