What is the difference between typeof and instanceof and when should one be used vs. the other?

Use instanceof for custom types: var ClassFirst = function () {}; var ClassSecond = function () {}; var instance = new ClassFirst(); typeof instance; // object typeof instance == ‘ClassFirst’; // false instance instanceof Object; // true instance instanceof ClassFirst; // true instance instanceof ClassSecond; // false Use typeof for simple built in types: ‘example … Read more

C++ equivalent of java’s instanceof

Try using: if(NewType* v = dynamic_cast<NewType*>(old)) { // old was safely casted to NewType v->doSomething(); } This requires your compiler to have rtti support enabled. EDIT: I’ve had some good comments on this answer! Every time you need to use a dynamic_cast (or instanceof) you’d better ask yourself whether it’s a necessary thing. It’s generally … Read more

The performance impact of using instanceof in Java

Approach I wrote a benchmark program to evaluate different implementations: instanceof implementation (as reference) object-orientated via an abstract class and @Override a test method using an own type implementation getClass() == _.class implementation I used jmh to run the benchmark with 100 warmup calls, 1000 iterations under measuring, and with 10 forks. So each option … Read more