![]() It simply checks that the type of each element expression is assignable to the array element type. The compiler does not note the types of the individual elements of an array. (I know this is a wrong design, but let's just assume I had to do this.) But we always know for sure that, say, element 0 is a Double, element 1 is a String. In terms of performance, the biggest hit in your scenario is liable to be cache misses from chasing object pointers all over the place (the type information will of course be common).įor example, suppose we have an array of Object, where each element might have a different type. Hopefully you can see that this sort of thing is largely irrelevant to performance. IN the very early days (over a decade ago), interfaces were a bit slow, but that is no longer relevant. ![]() Generally the last two casts to interfaces are cached in the runtime type. Interfaces are more difficult due to multiple inheritance of interface. ISAs such as 32-bit ARM have conditional instruction and may be able to have the sad path pass through the happy path. Depending upon instruction set architecture, another instruction will need to branch (or fault) on an incorrect branch. Then the read value just needs a comparison to the expected static type of the cast. Again this is analogous to reading a method pointer for a virtual method. This is necessary for calling a virtual method in a similar situation anyway.įor casting to a class type, it is known exactly how many superclasses there are until you hit, so the type can be read at a constant offset from the type pointer (actually the first eight in HotSpot). Assuming the runtime compiler (generally HotSpot in Sun's case) cannot determine the type statically a some checking needs to be performed by the generated machine code.įirst that pointer to the runtime type needs to be read. Taken from JavaWorld: The cost of castingĮach object has a header containing, amongst other things, a pointer to the runtime type (for instance Double or String, but it could never be CharSequence or AbstractList). In this second case, there is overhead in runtime, because the two types must be checked and in case that casting is not feasible, JVM must throw a ClassCastException. String s = (String) o // explicit casting For this case, you must explicitly use casting like that: Object o = someObject Implicit casting, when you cast from a type to a wider type, which is done automatically and there is no overhead: String s = "Cast" Įxplicit casting, when you go from a wider type to a more narrow one.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |