- Unity 2017 Game Optimization(Second Edition)
- Chris Dickinson
- 333字
- 2021-07-02 23:21:07
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.
- Python自動化運維快速入門
- C語言程序設計實訓教程
- HTML5+CSS3基礎開發教程(第2版)
- Java游戲服務器架構實戰
- INSTANT Weka How-to
- NumPy Essentials
- 編寫高質量代碼:改善C程序代碼的125個建議
- Mastering Google App Engine
- WordPress 4.0 Site Blueprints(Second Edition)
- 編程與類型系統
- Xcode 6 Essentials
- SwiftUI極簡開發
- 關系數據庫與SQL Server 2012(第3版)
- SQL Server 2014 Development Essentials
- RESTful Web API Design with Node.js