Android 内存使用 - 我需要取消静态变量吗?

Android memory usage - Do i need to nullify static variables?

我目前正在对我的应用程序进行内存扫描,我只是有一个快速的问题,即当不再需要 class 时如何处理 class 中的 public static 变量.一个例子是网络请求:

public class NetworkRequest {

    public static String URL = "www.somestring.com/endpoint?withsomeparameters=true"

    public void perform(){
         // the rest of the request logic...
    }
}

在我启动这个 class 之后:

NetworkRequest networkRequest = new NetworkRequest();

networkRequest.perform();
networkRequest = null;

我的 public static 字段是否阻止此 class 被正确垃圾收集?

然后再问同样的问题:

再次感谢您的帮助

没有。您的 class 可以在不再使用时被垃圾回收。该静态字段是使用字符串的 class,而不是使用您的 class.

的字符串

不,那个静态成员没有问题。如果无法到达该对象,垃圾收集器仍然可以对其进行处理。

All objects in Java exist either on the heap or on the stack. Objects are created on the heap with the new operator. A reference is then attached to them. If the reference becomes null or falls out of scope (e.g., end of block), the GC realizes that there is no way to reach that object ever again and reclaims it. If your reference is in a static variable, it never falls out of scope but you can still set it to null or to another object.

静态变量作为 GC 的 "roots"。因此,除非您明确将它们设置为 null,否则它们将在程序存在时存在,并且从它们可以访问的所有内容也是如此。