CodeBunny
CodeBunny

Reputation: 2031

Is there a performance hit upon object instantation if the object has many methods?

Just a bit of idle curiosity here.

Basically, if I have an object that only has a few primitive data members, it takes up a small amount of memory and doesn't take very long at all to create. However, what happens if I have a lot of methods associated with that object? Does object instantiation have to take those into account at all?

For example, let's say I have a Class with (insert absurdly large number here) number of distinct methods I can call. Does the JVM take any longer to make an instance of that class than if I had no methods?

Upvotes: 4

Views: 152

Answers (3)

tletnes
tletnes

Reputation: 1998

I can't speak for java, but in C++ etc. non-virtual methods can be stored as global functions (wth approriate name mangling) and don't need extra space at instantiation time. Virtual methods will have to be filled into the VMT, which can probably be built at compile time and a single pointer stored in the object at instantiation.

So no, I don't see any hit for large numbers of methods.

Upvotes: 3

duffymo
duffymo

Reputation: 308743

No, I don't believe there's a performance hit that'll be measurable or matter to you. I'd say no and defy you or anyone else to come back with meaningful data to the contrary.

If your object is that big, I'd say it's time to refactor.

Upvotes: 2

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340713

No, Class with methods is stored once in a separate memory location (namely PermGen) and each object of a given class has only a single reference to its type (Class).

Thus it doesn't matter how many methods your object has: two or two thousand - the object creation will take exactly the same amount of time.

BTW the same holds true for method invocation - there is no performance hit when calling methods of an object having plenty of them compared to object having only few.

See also

Upvotes: 6

Related Questions