title: java optimization nitpick: is it faster to cast something and let it throw exception than calling instanceof to check before cast?
body: <p>Before anyone says anything I'm asking this out of curiosity only; I'm not planning to do any premature optimization based off of this answer.</p>
  
  <p>My question is about speed in using reflection and casting.  The standard saying is 'reflection is slow'.  My question is what part exactly is slow, and why; particularly in comparing if something is a parent of another instance.</p>
  
  <p>I'm pretty confident that just comparing the class of an object to another Class object is about as fast as any comparison, presumably just doing direct comparison of singleton objects that are already stored int he Object's state; but what if one class is a parent of the other?</p>
  
  <p>I usually think of <code>instanceof</code> as being about as fast as regular class checking, but today I thought about it and it seems that some reflection has to happen 'under the scenes' for <code>instanceof</code> to work.  I checked online and found a few places where someone said <code>instanceof</code> is slow; presumably due to reflection required to compare the parent of an object?  </p>
  
  <p>This lead to the next question, what about just casting.  If I cast something as an object it's not I get a <code>ClassCastException</code>.  But this doesn't happen if a cast an object to a parent of itself. Essentially I'm doing an <code>instanceof</code> call, or logic to that effect, when I do the cast at run time am I not?  I've never heard anyone hint that casting an object could be slow before.  Admittedly not all casts are to a parent of the provided object, but plenty of casts <em>are</em> to parent classes.  Yet never has anyone hinted at all that this could be slow.</p>
  
  <p>So which is it. Is <code>instanceof</code> really not that slow?  Are both <code>instanceof</code> and casting to parent class kind of slow?  or is there some reason a cast can be done faster then an <code>instanceof</code> call?</p>