Faster GameObject null reference checks
It turns out that performing a null
reference check against a Unity object invokes a method on the other side of the native-managed bridge (mentioned earlier and explored in more detail in Chapter 7, Masterful Memory Management), which, as expected, results in some unnecessary performance overhead:
if (gameObject != null) { // do stuff with gameObject }
There is a simple alternative that generates a functionally equivalent output, but operates around twice as quickly (although it does obfuscate the purpose of the code a little):
if (!System.Object.ReferenceEquals(gameObject, null)) { // do stuff with gameObject }
This applies to both GameObjects and Components, as well as other Unity objects, which have both ...
Get Unity 5 Game Optimization now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.