| Author |
Cost of Casting
|
Mark Herschberg
Sheriff
Joined: Dec 04, 2000
Posts: 6037
|
|
I know that using the instanceOf() operator is slow (thanks to Peter Haggar's book :-) I've been taught that casting is expensive. Some questions linger. 1. How expensive is it? 2. Do JVMs typically do it using instanceOf()? 3. Is there a cost difference between upcasting and downcasting? If so, what is it and why? 4. Are upcasts to Object not checked, because they should always be true (for any object, not for primatives, of course)? 5. Any other tricky points with casting? Enquiring minds want to know! Thanks for any help. --Mark hershey@vaultus.com
|
 |
Jack Shirazi
Author
Ranch Hand
Joined: Oct 26, 2000
Posts: 96
|
|
I don't know that instanceOf is slow. I've found it to be a pretty fast operation. Type casts are essentially a call to instanceof, so there is every reason to optimize it in the JVM. A cast like <PRE> ClassX x = (ClassX) y; </PRE> is essentially a test like <PRE> if ( (y == null) | | (y instanceof X) ) assign y to x else throw a class cast exception </PRE> Primitive casts are different of course. They are a bitmap conversion operation, with no test involved. Upcasts are normally eliminated by the compiler. Writing <PRE> Integer i = new Integer(1); Number n = (Integer) i; </PRE> normally gets compiled as if written as <PRE> Integer i = new Integer(1); Number n = i; </PRE> There is a section on casts and their costs containing more info in my book (go to your bookstore and flick to page 167) --Jack Shirazi http://www.JavaPerformanceTuning.com/
|
 |
Peter Haggar
author
Ranch Hand
Joined: Jan 03, 2001
Posts: 106
|
|
Actually, I don't say using instanceof is slow in my book. That was my initial assumption, but my tests proved otherwise so I was (hopefully) careful not to give this impression in the book. (If I missed something, please let me know where.) My arguments against instanceof were from a design perspective. Polymorphism is the better way to go...usage of instanceof cannot always be avoided, but should be minimized. Although I didn't write about it, my tests back up Jack's findings. Peter Haggar ------------------ Senior Software Engineer, IBM author of: Practical Java
|
Senior Software Engineer, IBM
author of: Practical Java
|
 |
Mark Herschberg
Sheriff
Joined: Dec 04, 2000
Posts: 6037
|
|
Originally posted by Peter Haggar: Actually, I don't say using instanceof is slow in my book. That was my initial assumption, but my tests proved otherwise so I was (hopefully) careful not to give this impression in the book. (If I missed something, please let me know where.) My arguments against instanceof were from a design perspective. Polymorphism is the better way to go...usage of instanceof cannot always be avoided, but should be minimized.
You're right. I misremembered the motivation for your comments, thinking it was speed instead of design. Sorry for the confusion. --Mark
|
 |
 |
|
|
subject: Cost of Casting
|
|
|