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!
Object creation in Java is one of the most expensive operation in terms of memory utilization and performance impact. It is thus advisable to create or initialize an object only when it is required in the code. Making a class field public can cause lot of issues in a program.
Instantiation: The new keyword is a Java operator that creates the object. Initialization: The new operator is followed by a call to a constructor, which initializes the new object.
Object creation is considered as costly because it consumes your memory.As a result of this, program will suffer from lack of resources(memory) and it become slow.
There are five different ways to create an object in Java: Java new Operator. Java Class. newInstance() method.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With