Earlier quoted context omitted.
Aha, I think I better understand your point: since the generated bytecode includes a cast, my explanation about the optimization is too simplistic. I haven't actually inspected the emitted bytecode, so I was only reasoning from the observed speedup. Your point about branch prediction is really interesting; it would explain how the cast becomes almost free once the type is stable in the hot path. I'm learning a lot fr…
Without seeing the actual differences in the bytecode it will be hard to tell what’s really going on. From my experience with other JITs, I’d expect the situation to be something like: A) Without the typecast, the compiler can’t prove anything about the type, so it has to assume a fully general type. This creates a very “hard” bytecode sequence in the middle of the hotpath which can’t be inlined or optimised. B) With…
But even with speculation, it shouldn't be that surprising that dynamic dispatch and reflection [0] are quite expensive compared to a cast and a field access of the length property.