Is casting expensive?

test is very limited, and kind of gives a poor impression of the true cost of casting. The casting function in source code is very simple, it reads the properties and function definitions of the Class and compares them to the properties and function definitions of the object passed in. If all of these things match, we have a successful cast. Depending on what you’re casting to could be very little, like the sample project here is doing as little as possible in the cast to minimize the apparent cost of it, or it could be a rather deep check up the V-Table with lots of data to sort through (it verifies the ENTIRE class, not just the last child, of course, that’s why a Character will cast to Actor or Pawn as well as Character). In a real project if you’re casting can be quite expensive, for example casting to your player character you’re most likely checking UObject/Actor/Pawn/Character/MyCharacterBase/MyHeroBase/MyHeroType. These classes are often quite large, everything you make on top of Character is not optimized for casting like the engine classes are, so they can get very expensive to cast.
The true advantage to using an interface is that you only have to find the function definitions in that interface in your object to know it implements it, so while in your test here the interface and class are so similar in size they might as well be the same, is likely never true in a real scenario.
I’ve done basic Fizz-Buzz testing for release builds of shipped games, and I can tell you with absolute certainty the smaller the interface and larger the class, the larger the discrepancy between using them becomes. So should you avoid class casting entirely? Well no, getting around casts entirely is a lot of systems design work and that production cost has to weigh in at some point in the discussion, and making a billion interfaces isn’t going to make your life any easier long term, so cast today and come back to redesign tomorrow when it’s a core or you do it very frequently, and build ecosystems that don’t require casting to function.

4 Likes