英文:
How JVM manages memory for methods?
问题
例如,我们有一个MyClass
的实例,它包含1个方法。这个方法应该保留在内存中。当这个MyClass
的实例被垃圾回收时,对这个方法的引用是否也被删除了?我想弄清楚通过依赖注入执行所有操作(因此创建每个类的新实例)是否需要更少的内存并且更高效,还是简单的具有大量静态方法的Helper
类仍然很好。
英文:
For example we have an instance of MyClass
and it contains 1 method. This method should be kept in memory. When this instance of MyClass
is being GC'ed, is a reference to this method being deleted as well? I want to figure out weather doing everything via Dependency Injection (hence creating new instances of every class) requires less memory and more efficient or simple Helper
classes with a bunch of static methods are still good.
答案1
得分: 1
对象的实例方法存储在其类对象中(应仅存在一份副本),它们不会随每个新实例而“复制”,相反,在幕后,每个实例都持有对存储在类对象中的方法实现的引用。
实例被垃圾回收,而不是类数据。类数据存储在permgen空间或metaspace中,具体取决于Java版本。
垃圾收集器专门在创建实例的堆上工作,而不是在permgen或metaspace上。
英文:
The instance methods of an object are stored in its class object (only one copy should exist), they are not "copied" with each new instance, instead, under the hood each instance holds a reference to the method implementation residing in the class object.
Instances are garbage collected not the class data. The class data gets stored in permgen space or metaspace depending on the java version.
Garbage collectors work specifically on the heap where the instances are created not on the permgen or metaspace.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论