26

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.

3 Answers 3

17

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.

1
1

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.

3
  • Reflection has gooten faster with each release of Java.
    – TofuBeer
    Mar 15, 2009 at 3:18
  • 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
    Mar 15, 2009 at 3:32
  • 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. Mar 16, 2009 at 11:41
-1

There's a difference - in 10 times. Absolute difference is tiny but if your write low latency application cumulative CPU time lost might be significant.

    long start, end;
    int X = 10000000;
    ArrayList l = new ArrayList(X);
    start = System.nanoTime();
    for(int i = 0; i < X; i++){
        String.class.newInstance();
    }
    end = System.nanoTime();
    log("T: ", (end - start)/X);

    l.clear();
    start = System.nanoTime();
    for(int i = 0; i < X; i++){
        new String();
    }
    end = System.nanoTime();
    log("T: ", (end - start)/X);

Output:

T: 105
T: 11

Tested on Xeon W3565 @ 3.2Ghz, Java 1.6

1
  • 3
    I would take a careful look at this code. During runtime, the java optimizer will simply stop executing new String() because it can tell doing so will have no side effects. It will not do the same for String.class.newInstance() because it is reflection and it cannot tell whether the newInstance factory class has side effects.
    – cmdematos
    Dec 6, 2013 at 22:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.