简体   繁体   English

类实例中的方法是否在内存中占有一席之地?

[英]Do methods in class instances take a place in memory?

When I have a class like this: 当我有这样的课程时:

class Test {
    private int _id  = 0 ; // 4 bytes
    private int _age = 0 ; // 4 bytes
}

I'm sure that each instance of it will consume more than 8 bytes in memory because of the 2 integers. 我确信它的每个实例在内存中消耗超过8个字节,因为它有2个整数。

But what about methods? 但是方法怎么样? If I have a class with a million methods, and 2 instances of it, are the methods going to take twice as much place in memory ? 如果我有一个拥有一百万个方法的类,以及它的两个实例,这些方法会占用内存的两倍吗?

How does it work? 它是如何工作的?

Thank you. 谢谢。

No. Methods occur only once in memory 1 . 不可以。方法只在内存1中出现一次。 They don't vary on a per instance basis, so they don't need storage on a per-instance basis. 它们不会每个实例而异 ,因此它们不需要基于每个实例进行存储

An object in Java basically consists of some fixed-size "housekeeping" (a pointer to the type information including the vtable), potentially GC-related bits (think mark and sweep), information about the monitor for the instance etc - and then the fields. Java中的对象基本上由一些固定大小的“内务处理”(指向类型信息的指针,包括vtable),可能与GC相关的位(思考标记和扫描),有关实例的监视器的信息等 - 然后是领域。


1 This is a bit of a simplification. 1这有点简化。 There may be various representations, such as bytecode, native code etc - but that's regardless of separate instances. 可能有各种表示形式,例如字节码,本机代码等 - 但这与单独的实例无关。

Having two instances of the same class does not duplicate the amount of space needed for the method code. 具有相同类的两个实例不会复制方法代码所需的空间量。 That is to say, the methods reside in one place in memory and then each instance of the class has a pointer pointing to that place in memory. 也就是说,这些方法驻留在内存中的一个位置,然后该类的每个实例都有一个指向内存中该位置的指针。 This is because otherwise memory would be wasted. 这是因为否则会浪费内存。 The code that needs to be executed for each method is the same, regardless of which instance of the class calls it, so it would make no sense to duplicate it. 无论类的哪个实例调用它,每个方法需要执行的代码都是相同的,因此复制它是没有意义的。

但是为了执行像instance.method()这样的方法,该方法的本地副本将在每个实例的堆栈中进行,其中实例将在堆中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM