Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do methods in class instances take a place in memory?

Tags:

java

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.

like image 873
Reacen Avatar asked Aug 02 '11 08:08

Reacen


People also ask

Are methods stored in memory?

Methods are stored somewhere else in the memory. Notice that methods are per-class, not per-instance. So typically, the number of methods doesn't change over the run-time of a program (there are exceptions). In traditional models, the place where the methods live is called the "code segment".

Where are instance methods stored?

The program is executed line by line, with jumps between methods. Execution causes the stored information to change. Static information (interface & class boxes) and instance information (object boxes) are stored in the heap. Method information is stored in the run-time stack.

Do classes take space in memory?

In general a class or struct is a concept and does not occupy variable (data) space, but it does take up memory in the compiler's memory.

Is a method an instance of a class?

An object that is created using a class is said to be an instance of that class. We will sometimes say that the object belongs to the class. The variables that the object contains are called instance variables. The methods (that is, subroutines) that the object contains are called instance methods.


1 Answers

No. Methods occur only once in memory1. 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.

like image 54
Jon Skeet Avatar answered Oct 17 '22 18:10

Jon Skeet