C#/Unity3d Tips & Tricks

I will update this page from time to time with tips & tricks regarding development with Unity3d or C#.
 

Comparing struct values

Optimize struct comparisons by comparing individual fields rather than calling equality operators. .Equals() is generally really slow, avoid it!
This is a small optimization, only necessary if you are indeed calling tens or hundreds of thousands of comparisons in a single frame.

var sw = new System.Diagnostics.Stopwatch();
var v3 = new Vector3(0, 0, 0);

sw.Start();
for (int i = 0; i < 100000; i++)
{
	var result = v3.Equals(Vector3.zero);
}
sw.Stop();
Debug.Log(".Equals(Vector3.zero): " + sw.ElapsedMilliseconds);

//Output: .Equals(Vector3.zero): 17ms

sw.Reset();
sw.Start();
for (int i = 0; i < 100000; i++)
{
  var result = v3 == Vector3.zero;
}
sw.Stop();
Debug.Log("== Vector3.zero: " + sw.ElapsedMilliseconds + "ms");

//Output: == Vector3.zero: 9ms

sw.Reset();
sw.Start();
for (int i = 0; i < 100000; i++)
{
  var result = v3.magnitude == 0;
}
sw.Stop();
Debug.Log("magnitude == 0: " + sw.ElapsedMilliseconds + "ms");

//Output: magnitude == 0: 3ms

sw.Reset();
sw.Start();
for (int i = 0; i < 100000; i++)
{
  var result = v3.x == 0 && v3.y == 0 && v3.z == 0;
}
sw.Stop();
Debug.Log("== 0,0,0: " + sw.ElapsedMilliseconds + "ms");

//Output: == 0,0,0: 1ms