Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does an instance method get loaded into memory per object or per class?

If I have an object O with a gigantic method f(), and I load 10000 examples of O into memory. Are 10000 examples of f() loaded into memory as well? If so, does that mean that I would save memory by making this function static if possible?

like image 529
pgsandstrom Avatar asked Feb 17 '11 16:02

pgsandstrom


People also ask

How do instance methods work?

Instance method are methods which require an object of its class to be created before it can be called. To invoke a instance method, we have to create an Object of the class in which the method is defined.

Can an instance method be called on an object?

Calling Instance Method: You can not call an instance method in the static method directly, so the Instance method can be invoked using an object of the class.

What is the difference between instance and class methods?

Instance methods need a class instance and can access the instance through self . Class methods don't need a class instance. They can't access the instance ( self ) but they have access to the class itself via cls .

Do methods take up memory?

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.


2 Answers

Instance Methods are loaded in to Method Area in JVM. it is loaded once , but there will be many stack for every call u make to f() , to keep track of there own local variable values.

like image 138
Dead Programmer Avatar answered Sep 23 '22 02:09

Dead Programmer


No. There is only one instance of the method loaded.

like image 21
qbert220 Avatar answered Sep 19 '22 02:09

qbert220