Reputation: 7731
I am hearing from another developer that an object is too expensive to instantiate repeatedly because "it has a bunch of methods."
My understanding (from Bloch, mostly) was that object creation is costly mostly through things done explicitly in the constructor, especially creating other expensive objects.
Is there a per-method cost for a new object in Java? I'm thinking not, but I need references if anyone has them.
Thanks!
Upvotes: 11
Views: 2650
Reputation: 61526
As an aside, there would be a slight performance hit for a class with many instance variables (not sure it would really be measurable though). Java requires each instance variable to be set to 0, false, null for each new instance and there is a runtime cost associated with setting them to zero. However it is probably just a memset (or calloc or something like that) which is fast to complete.
Upvotes: 1
Reputation: 28059
No, there is no relationship between the number of methods on a class and the time for the JVM to perform a new
operation.
Seriously, if you are thinking at this sort of level you shouldn't be using a language like Java, go and write your application in assembler or 'C'.
The truth is you should concentrate on the design of your algorithms and data structures, these will have a much more profound effect on your applications performance than any potential micro optimisation.
Upvotes: 3
Reputation: 60190
Many methods means a big virtual method table (VMT). However, the VMT is per class just like metadata and therefore does only have at most a one-time cost on the very first instantiation. Subsequent instantiations are just as fast as objects with less methods, assuming that the constructor(s) do not do heavy lifting.
Worth a read is also the chapter on object creation from the performance tuning book.
Upvotes: 13