mercredi 20 juin 2018

Java: instanceof vs class name switch performance

I was interested in performance question about determine type of object and write some benchmarks with 2 ways of determination.

Can someone explain me why variant with instanceof faster 350 times than variant with class name switching with strings?

Code:

class A {}
class B extends A {}

public class InstanceOfBenchmark {
    public static final Object a = new A();

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.MICROSECONDS)
    public void testInstanceOf()
    {
        if (a instanceof B) {}
        else if (a instanceof String) {}
        else if (a instanceof ArrayList) {}
        else if (a instanceof HashMap) {}
        else if (a instanceof HashSet) {}
        else if (a instanceof A);
    }

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.MICROSECONDS)
    public void testName() {
        String class_name = a.getClass().getSimpleName();

        switch (class_name) {
            case ("B") :
            case ("String") :
            case ("ArrayList") :
            case ("HashMap") :
            case ("HashSet") :
            case ("A") :
        }
    }

    public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder()
                .include(InstanceOfBenchmark.class.getSimpleName())
                .warmupIterations(20)
                .measurementIterations(100)
                .forks(1)
                .build();

        new Runner(opt).run();
    }
}

Results:

Benchmark                            Mode  Cnt     Score    Error   Units
InstanceOfBenchmark.testInstanceOf  thrpt  100  3482.001 ± 25.447  ops/us
InstanceOfBenchmark.testName        thrpt  100    10.579 ±  0.078  ops/us

I run tests with 200 times warmup and 2000 iteration too, result was same.





Aucun commentaire:

Enregistrer un commentaire