Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

newInstance() vs new

Is there a penalty for calling newInstance() or is it the same mechanism underneath? How much overhead if any does newInstance() have over the new keyword* ?

*: Discounting the fact that newInstance() implies using reflection.

like image 501
javito Avatar asked Sep 10 '25 21:09

javito


1 Answers

In a real world test, creating 18129 instances of a class via "Constuctor.newInstance" passing in 10 arguments -vs- creating the instances via "new" the program took no measurable difference in time.

This wasn't any sort of micro benchmark.

This is with JDK 1.6.0_12 on Windows 7 x86 beta.

Given that Constructor.newInstance is going to be very simlilar to Class.forName.newInstance I would say that the overhead is hardly anything given the functionality that you can get using newInstance over new.

As always you should test it yourself to see.

like image 50
TofuBeer Avatar answered Sep 12 '25 09:09

TofuBeer