본문 바로가기

Language/자바

isInstanceOf vs isAssignable

http://stackoverflow.com/questions/496928/what-is-the-difference-between-instanceof-and-class-isassignablefrom 참조




가장 심플한 설명이다.



1. 개념


이 개념이 제일 확실하다. java oracle 문서에 이렇게 설명이 되있다. 이게 핵심이다.


instanceof can only be used with reference types, not primitive types. isAssignableFrom() can be used with any class objects:

a instanceof int  // syntax error
3 instanceof Foo  // syntax error
int.class.isAssignableFrom(int.class)  // true


2. 성능


성능은 물론 instanceof 가 빠름.



class A{}
class B extends A{}

A b = new B();

void execute(){
   boolean test = A.class.isAssignableFrom(b.getClass());
   // boolean test = A.class.isInstance(b);
   // boolean test = b instanceof A;
}

@Test
public void testPerf() {
    // Warmup the code
    for (int i = 0; i < 100; ++i)
        execute();

    // Time it
    int count = 100000;
    final long start = System.nanoTime();
    for(int i=0; i<count; i++){
       execute();
    }
    final long elapsed = System.nanoTime() - start;
    System.out.println(count+" iterations took " + TimeUnit.NANOSECONDS.toMillis(elapsed) + "ms.);
}

It gives :

  • A.class.isAssignableFrom(b.getClass()) : 100000 iterations took 15ms
  • A.class.isInstance(b) : 100000 iterations took 12ms
  • b instanceof A : 100000 iterations took 6ms

So that we can conclude instanceof is faster !

'Language > 자바' 카테고리의 다른 글

자바 Comparator 구현  (0) 2016.10.25
객체지향의 개념  (0) 2016.09.26
Java Stream / marshal, unmarshal / serializable / NIO  (0) 2016.09.05
2Phase Commit  (0) 2016.08.17
JVM Locale  (0) 2016.06.23