静态方法内存消耗 [英] Static Methods Memory Consumption

查看:70
本文介绍了静态方法内存消耗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过以下方法使用以下类:

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");
       ....
   }
 }

如果Bar类在使用上述代码的过程中创建Foo,Foo会超出范围并收集垃圾,还是Foo(因为它使用静态方法)继续引用变量newFoo,因此将另一个对Foo的引用永远不会超出范围?

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?

推荐答案

静态方法的存在不会影响对象是否具有使用GC的资格,只有对对象的引用才会影响.在您的情况下,anotherFoo将是唯一参考.方法返回时,引用newFoo超出范围,弹出堆栈.

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.

SomeMethod返回时,anotherFoo后面的基础对象将有资格使用GC(好吧,当代码中不再使用anotherFoo时,编译器更具攻击性,并且可以使其可用于GC).

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

这篇关于静态方法内存消耗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆