Test Outcome:
- Checking if a variable is null with "if(myObject)" is about 10x more costly than doing "if(System.Object.ReferenceEquals(myObject, null))". The ReferenceEquals method is even faster than checking if a bool is true/false.
- A successful cast is more expensive than an unsuccessful cast
- Casting is a relatively light operation. It is about as light as checking "if(myObject == null)". But this might vary with the size of the object (?)
The Test:
The following test:
public bool testBool1 = false;
public bool testBool2 = true;
public Collider testSphereCollider;
public Collider testBoxCollider;
public Collider testNullCollider;
public void Awake()
{
Stopwatch watch = new Stopwatch();
watch.Reset();
watch.Start();
for (int i = 0; i < 10000000; i++)
{
if (testBool1 == testBool2)
{ }
}
watch.Stop();
UnityEngine.Debug.Log("Comparing bools " + watch.ElapsedMilliseconds.ToString());
watch.Reset();
watch.Start();
for (int i = 0; i < 10000000; i++)
{
if (testSphereCollider)
{ }
}
watch.Stop();
UnityEngine.Debug.Log("Checking null on testSphereCollider " + watch.ElapsedMilliseconds.ToString());
watch.Reset();
watch.Start();
for (int i = 0; i < 10000000; i++)
{
if (testNullCollider)
{ }
}
watch.Stop();
UnityEngine.Debug.Log("Checking null on testNullCollider " + watch.ElapsedMilliseconds.ToString());
watch.Reset();
watch.Start();
for (int i = 0; i < 10000000; i++)
{
if (System.Object.ReferenceEquals(testSphereCollider, null))
{ }
}
watch.Stop();
UnityEngine.Debug.Log("Checking null on testSphereCollider with ReferenceEquals " + watch.ElapsedMilliseconds.ToString());
watch.Reset();
watch.Start();
for (int i = 0; i < 10000000; i++)
{
if (System.Object.ReferenceEquals(testNullCollider, null))
{ }
}
watch.Stop();
UnityEngine.Debug.Log("Checking null on testNullCollider with ReferenceEquals " + watch.ElapsedMilliseconds.ToString());
watch.Reset();
watch.Start();
for (int i = 0; i < 10000000; i++)
{
if (testSphereCollider as SphereCollider)
{ }
}
watch.Stop();
UnityEngine.Debug.Log("Casting testSphereCollider to SphereCollider " + watch.ElapsedMilliseconds.ToString());
watch.Reset();
watch.Start();
for (int i = 0; i < 10000000; i++)
{
if (testBoxCollider as SphereCollider)
{ }
}
watch.Stop();
UnityEngine.Debug.Log("Casting testBoxCollider to SphereCollider " + watch.ElapsedMilliseconds.ToString());
watch.Reset();
watch.Start();
for (int i = 0; i < 10000000; i++)
{
if (testNullCollider as SphereCollider)
{ }
}
watch.Stop();
UnityEngine.Debug.Log("Casting testNullCollider to SphereCollider " + watch.ElapsedMilliseconds.ToString());
}
Outputs this: