官术网_书友最值得收藏!

Faster GameObject null reference checks

It turns out that performing a null reference check against a GameObject will result in some unnecessary performance overhead. GameObjects and MonoBehaviours are special objects compared to a typical C# object in that they have two representations in memory: one exists within the memory managed by the same system managing the C# code we write (Managed code), whereas the other exists in a different memory space which is handled separately (Native code). Data can move between these two memory spaces, but each time this happens will result in some additional CPU overhead and possibly an extra memory allocation.

This effect is commonly referred to as crossing the Native-Managed Bridge. If this happens, it is likely to generate an additional memory allocation for an object’s data to get copied across the Bridge, which will require the Garbage Collector to eventually perform some automatic cleanup of memory for us. This subject will be explored in much more detail in Chapter 8, Masterful Memory Management, but for the time-being just consider that there are many subtle ways to accidentally trigger this extra overhead, and a simple null reference check against a GameObject is one of them:

if (gameObject != null) {
// do stuff with gameObject
}

An alternative that generates a functionally equivalent output which operates around twice as quickly (although it does obfuscate the purpose of the code a little) is System.Object.ReferenceEquals():

if (!System.Object.ReferenceEquals(gameObject, null)) {
// do stuff with gameObject
}

This applies to both GameObjects and MonoBehaviours, as well as other Unity objects, which have both Native and Managed representations like the WWW class. However, some rudimentary testing reveals that either null reference check approach still consumes mere nanoseconds on an Intel Core i5 3570K processor. So, unless you are performing massive amounts of null reference checks, the gains might be marginal at best. However, this is a warning worth keeping in mind for the future, as it will come up a lot.

主站蜘蛛池模板: 策勒县| 白水县| 安图县| 吉安市| 嘉禾县| 镇雄县| 三台县| 微山县| 连城县| 武平县| 手机| 息烽县| 鹤山市| 老河口市| 唐河县| 紫阳县| 峡江县| 三台县| 芮城县| 丰顺县| 德惠市| 团风县| 祁连县| 清流县| 遂平县| 渭南市| 阿克陶县| 丰原市| 库伦旗| 安庆市| 阿拉善盟| 余江县| 婺源县| 辰溪县| 潮州市| 吴川市| 晋江市| 高邑县| 报价| 阿勒泰市| 潞城市|