views:

1120

answers:

3

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.

A: 

Be wary of microbenchmarks, but I found this blog entry where someone found that new was about twice as fast as newInstance with JDK 1.4. It sounds like there is a difference, and as expected, reflection is slower. However, it sounds like the difference may not be a dealbreaker, depending on the frequency of new object instances vs how much computation is being done.

Eddie
Reflection has gooten faster with each release of Java.
TofuBeer
Yes, indeed, which is why I mentioned use of 1.4 in the benchmark I found. I'm sure that newInstance is still slower, but I'd be surprised if it were a huge difference.
Eddie
Calling setAccessible(true) on the Constructor should make it slightly faster (but make sure still secure). Of course, I'd suggest avoiding reflection if possible in any case.
Tom Hawtin - tackline
A: 

It is likely that any overhead newInstance() may have will be so insignificant it does not matter if you use it. Though if it comes down between which is faster new is probably the faster one.

Anton
+5  A: 

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.

TofuBeer
Check out http://www.ibm.com/developerworks/java/library/j-jtp02225.html ... these sorts of benchmarks are very difficult to get right due to the dynamic way that code is compiled/optimized by the JVM.
Eddie
Like I said, it was a real world example, not a micro benchmark...
TofuBeer