property perfomance

Hello, I want to ask what is better, this

private BoxCollider col
{
      get
      {
              return GetComponent<BoxCollider>();
      }
}

or get component in Start function as people usually do?

The key here is you want to cache the component. Something like this

BoxCollider _boxCollider;
BoxCollider boxCollider;
{
      get
      {
              if (!_boxCollider)
              {
                  _boxCollider = GetComponent<BoxCollider>();
              }
              return _boxCollider;
      }
}

or this

BoxCollider boxCollider;

void Awake ()
{
            _boxCollider = GetComponent<BoxCollider>();
}

Will be pretty close in performance. The first will be slightly more expensive due to the extra method call, but it won’t be noticeable unless you call it thousands of times per frame.

Your code will be more expensive then both, because you call GetComponent every time instead of just once.

1 Like