Is there any runtime cost for Casting in Java?

Well, the compiled code probably includes the cast twice in the second case – so in theory it’s doing the same work twice. However, it’s very possible that a smart JIT will work out that you’re doing the same cast on the same value, so it can cache the result. But it is having to do work at least once – after all, it needs to make a decision as to whether to allow the cast to succeed, or throw an exception.

As ever, you should test and profile your code if you care about the performance – but I’d personally use the first form anyway, just because it looks more readable to me.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)