开发者

Static Methods Memory Consumption

开发者 https://www.devze.com 2023-04-02 15:22 出处:网络
I have the following class with the following methods: public class Foo { public string A {get;set;} public static Foo New(string a)

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");
       ....
   }
 开发者_JAVA百科}

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?


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号