Skip to content

Avoid usage of GetComponent methods in performance critical context

Matt Ellis edited this page Feb 15, 2019 · 2 revisions

The various different GetComponent methods will return a component attached to the GameObject, if available. This lookup will return all components, or filter by type, and can walk the transform hierarchy. These methods can allocate memory, and have a high lookup cost, and should be avoided inside a performance critical context or risk per-frame allocations and poor performance.

It is recommended to move the call to Start and cache the results, or to use a direct reference. Some functions such as GameObject.GetComponentsInChildren allow for providing a list to store results, which can remove the per-frame allocations, but the performance of lookup is still high, so only use this if lookup is unavoidable.

This inspection will add a performance indicator highlight to a method call inside a performance critical context. It will also provide Alt+Enter context actions to move the call to Start or Awake and introduce a field to hold the cached result.

This inspection was first added in Rider/ReSharper 2018.3

Clone this wiki locally