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 native and managed representations. However, some rudimentary testing reveals that either approach still consumes mere nanoseconds on an Intel Core i5 3570K processor. So, unless you are performing massive amounts of null reference checks, then the gains might be marginal at best.

However, it is noteworthy in the sense that there can be many other simple alternatives that have yet to be discovered, which can help improve performance by circumventing the native-managed bridge.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.56.29