I assumed that caching the variable is faster than using the gameObject
variable from the Component
class and a simple test proved that to be true. That's because caching it will give you the reference rather than using gameObject
which uses the get
accessor to return the reference. Not sure if getting the reference requires a native function call but that's a possibility. Using get
accessor is slower than direct reference access.
Let's say you have 1 million scripts calling gameObject.activeSelf
or through the cached version _GameObject.activeSelf
.
Test Result:
gameObject: 54
ms
Cached _GameObject: 30
ms
Software/Hardware tested on:
- Unity 5.6.0f3
- Windows 10 Pro
- MacBookPro11,4
- 16 GB RAM
Does it matter?
In a normal app, maybe not. In a game, yes. Removing 24ms
from a game is a good improvement depending on the kind of Game.
Test script:
public GameObject _GameObject;
void Start()
{
Application.runInBackground = true;
int iterations = 1000000;
//TEST 1
Stopwatch stopwatch1 = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
bool active = gameObject.activeSelf;
}
stopwatch1.Stop();
//TEST 2
Stopwatch stopwatch2 = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
bool active = _GameObject.activeSelf;
}
stopwatch2.Stop();
//SHOW RESULT
WriteLog(String.Format("gameObject: {0}", stopwatch1.ElapsedMilliseconds));
WriteLog(String.Format("Cached _GameObject: {0}", stopwatch2.ElapsedMilliseconds));
}
void WriteLog(string log)
{
UnityEngine.Debug.Log(log);
}