Is casting expensive?

I was curious about too, so I went ahead and did some actual tests to find out. The results were that the difference is minimal, but that casting is in fact slightly faster than interfaces. In a real-world scenario however, there is no reason to worry about it, and it’s probably safe to say that is at the very bottom of the list of things to consider for optimization. One might argue it’s not even on that list at all.

DATA

On an empty scene playing in the editor, eyeballing the FPS stats read-out, it looks like :

Running 10 000 casts + function calls per frame takes 79 - 85 milliseconds/frame
Running 10 000 interface calls per frame takes 81 - 89 milliseconds/frame

So, there’s some overlap in those time intervals, but on average the cast approach is marginally faster. test was run on a laptop with a 460M and 6 GB of RAM, so the absolute numbers are not interesting here, only the relative difference. There’s also the rendering overhead to take into account, which on system was around 20 ms.

TEST SETUP

The level blueprint uses OnTick to run a for-loop that either calls an interface function, or performs a cast followed by a function call. The execution wire is moved manually to one or the other cases between tests:

The functions do something, but as little as possible:

If you want to try it out yourself, the project can be downloaded here: https://dl.dropboxusercontent.com/u/2888286/CastVSInterface.zip

10 Likes