dimanche 26 novembre 2017

java-why new() slower than newInstance()

i know that if i create new objects with reflection,it is very slow ,so i test it.but the result makes  me puzzled,newInstance() is faster than new(),my jdk version is java version "1.8.0_77".

public class Test {

static class B {
}

public static long timeDiff(long old) {
    return System.nanoTime() - old;
}

public static void main(String args[]) throws Exception {

    int numTrials = 10000000;
    B[] bees1 = new B[numTrials];
    Class<B> c = B.class;
    long nanos;
    nanos = System.nanoTime();
    for (int i = 0; i < numTrials; i++) {
        bees1[i] = new B();
    }
    System.out.println("Normal instaniation took: " + TimeUnit.NANOSECONDS.toMillis(timeDiff(nanos)) + "ms");
    B[] bees2 = new B[numTrials];
    nanos = System.nanoTime();
    for (int i = 0; i < numTrials; i++) {
        bees2[i] = c.newInstance();
    }
    System.out.println("Reflecting instantiation took:" + TimeUnit.NANOSECONDS.toMillis(timeDiff(nanos)) + "ms");

}

}

the result:

  • Normal instaniation took: 2363ms
  • Reflecting instantiation took:1679ms.

so i don't know why..who can explain it ?





Aucun commentaire:

Enregistrer un commentaire