字符串和静态字段是否被垃圾回收?

发布于 2024-11-27 04:34:11 字数 83 浏览 0 评论 0原文

垃圾收集器何时回收字符串和静态字段?

我问这个问题是因为我知道 ASP.NET 中的static始终是活动的。

When do strings and static fields get reclaimed by the garbage collector?

I'm asking this because I know statics in ASP.NET are always live.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

℉絮湮 2024-12-04 04:34:11

垃圾收集器仅收集不可访问的对象。静态字段引用的对象在其类加载后即可访问,因此显然不会被收集(当然,除非该字段被设置为引用其他内容,导致原始对象可能有资格被收集)。

至于字符串,则视情况而定。文字字符串被保留,因此始终可以访问。否则,相同的规则适用于任何对象。

The garbage collector only collects objects that are not accessible. An object referenced by a static field is accessible as soon as its class is loaded, so it will obviously not get collected (unless of course the field is set to refer to something else, causing the original object to become potentially eligible for collection).

As for strings, it depends. Literal strings are interned and therefore always accessible. Otherwise, same rules apply as for any object.

私野 2024-12-04 04:34:11

字符串是对象,未引用时将被收集。

静态字段通常保留对对象的永久引用,从而防止这些对象被收集。但只要您仍然需要这些对象就没有问题。

Strings are objects and will be collected when un-referenced.

static fields usually keep a permanent reference to an object and thus keep those objects from being collected. But as long as you still need those objects that's quite alright.

べ繥欢鉨o。 2024-12-04 04:34:11

任何引用对象的static 字段都会阻止该对象被收集,因为static 字段与类的Type 对象相关联。这些依次与 AppDomain 关联,因此将充当 GC 根。

对于字符串,它取决于它是否已被实习。如果有,则当前 AppDomain 的实习池将引用它,从而阻止收集。如果不是,那么字符串将像任何其他类对象一样运行,并且当不再可以通过 GC 根的引用链访问它时,它就可以被回收。

请注意,在这两种情况下,如果 AppDomain 被卸载,则对象将符合收集条件。

Any static field that references an object will prevent that object from being collected, since static fields are associated with the Type object for a class. Those in turn are associated with an AppDomain, and thus will serve as GC roots.

For strings, it is dependent on whether or not it has been interned. If it has, then the intern pool for the current AppDomain will reference it and thus prevent collection. If not, then a string will behave like any other class object, and be eligible for collection when it is no longer accessible via a chain of references from a GC root.

Note that in both cases, if the AppDomain is unloaded, the objects will become eligible for collection.

眼睛会笑 2024-12-04 04:34:11

不,垃圾收集器不会收集静态字段。一般来说,只要类的实例存在并且指向它就会保留,垃圾收集就不会收集您的类。

No, the garbage collector will not collection the static fields. in general the garbage collection will not collection you classes as long as an instance of your class exists and is pointed to it will stay.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文