Test Outcome

  • Checking if a GameObject has a component through GetComponent is about 4-5x slower than checking by having it cached.
  • 1 milion GetComponents takes about 60 ms, which means it isn't that terrible for performance
  • The number of components on a GameObject doesn't affect GetComponent performance

The Test

public class GetComponentTest : MonoBehaviour
{
    public GameObject objectWithComponent;
    public GameObject objectWithoutComponent;
    public TestComponent cachedComponent;

    public const int iterations = 1000000;

    private TestComponent _queriedComponent;

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Stopwatch watch = new Stopwatch();

            watch.Reset();
            watch.Start();
            for (int i = 0; i < iterations; i++)
            {
                _queriedComponent = objectWithComponent.GetComponent<TestComponent>();
            }
            watch.Stop();
            UnityEngine.Debug.Log("GetComponent on object that has it " + watch.ElapsedMilliseconds.ToString());

            watch.Reset();
            watch.Start();
            for (int i = 0; i < iterations; i++)
            {
                _queriedComponent = objectWithoutComponent.GetComponent<TestComponent>();
            }
            watch.Stop();
            UnityEngine.Debug.Log("GetComponent on object that doesn't have it " + watch.ElapsedMilliseconds.ToString());

            watch.Reset();
            watch.Start();
            for (int i = 0; i < iterations; i++)
            {
                _queriedComponent = this.GetComponent<TestComponent>();
                if (_queriedComponent)
                { }
            }
            watch.Stop();
            UnityEngine.Debug.Log("Checking if object has component through GetComponent " + watch.ElapsedMilliseconds.ToString());

            watch.Reset();
            watch.Start();
            for (int i = 0; i < iterations; i++)
            {
                if (cachedComponent)
                { }
            }
            watch.Stop();
            UnityEngine.Debug.Log("Checking if object has component through cached component " + watch.ElapsedMilliseconds.ToString());
        }
    }
}

, w

results matching ""

    No results matching ""