简体   繁体   中英

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.

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


1 This is a bit of a simplification. 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()这样的方法,该方法的本地副本将在每个实例的堆栈中进行,其中实例将在堆中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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