Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a per-method cost to object instantiation in Java?

Tags:

java

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!

like image 869
orbfish Avatar asked Jul 09 '10 22:07

orbfish


People also ask

Is object creation costly in Java?

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.

How is an object instantiated in Java?

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.

Is object creation expensive?

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.

How many ways we can instantiate object in Java?

There are five different ways to create an object in Java: Java new Operator. Java Class. newInstance() method.


2 Answers

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.

like image 170
Lucero Avatar answered Sep 30 '22 04:09

Lucero


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.

like image 21
Gareth Davis Avatar answered Sep 30 '22 02:09

Gareth Davis