简体   繁体   中英

what is more performant equal or instanceof?

Which method is performanter to use?

equals:

public boolean hasSellByDate(Object item) {
  if ("Pear".equals(item.getClass().getSimpleName())) {
    return true;
  }
  return false;
}

instanceof:

public boolean hasSellByDate(Object item) {
   if (item instanceof food.Pear) {
     return true;
   }
   return false;
 }

What differences do these two methods have and what disadvantages are there in each case?

The second one if far superior because the first can be broken by refactoring, and the type-system will not let you know.

You should also be aware that the first method will not work for subclasses of Pear , should you have any. Even worse, it might be confused if you have multiple classes called "Pear" in different namespaces.

As for performance, you will need to benchmark, but I would expect the second to also be faster, since instanceof is a single opcode on the JVM ( https://en.wikipedia.org/wiki/Java_bytecode_instruction_listings ).

I would like to add other two snippets to your list. So four options would look like below.

Please mind that all four options are functionally different!

#1

public boolean hasSellByDate(Object item) {
  if ("Pear".equals(item.getClass().getSimpleName())) {
    return true;
  }
  return false;
}

#2

public boolean hasSellByDate(Object item) {
  if (item instanceof food.Pear) {
    return true;
  }
  return false;
}

#3

public boolean hasSellByDate(Object item) {
  if ("food.Pear".equals(item.getClass().getName())) {
    return true;
  }
  return false;
}   

#4

public boolean hasSellByDate(Object item) {
  if (item.class == food.Pear) {
    return true;
  }
  return false;
}

Performancewise (at least in OpenJDK HotSpot JVM):

  • #4 is the fastest
  • #2 and #3 would be close, #2 is likely to be fastest after round of JIT compilation
  • #1 could be real performance bottleneck especially in multi threaded environment

Class.getSimpleName() could be unreasonable slow due to global critical section and string manipulation. I've seen it once being a real performance bottleneck. Method was used for formatting log messages.

Stylewise, I would recommend #2 and #4 dependent on functional needs.

And to stress one more time, all four options are functionally different!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM