Skip to content

Avoid usage of AddComponent in performance critical code

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

Calling GameObject.AddComponent is expensive, especially inside a performance critical context. Each time a component is added, the following must happen:

  1. Finding the component's script in the script cache, by name. This might also incur allocations if it's not already cached.
  2. Allocating the memory for the MonoBehaviour.
  3. Notifying other attached components that a new component has been added. The attached components can perform actions when a known component is added. The amount of work performed here depends on the number and type of attached components. E.g. a rigid body needs to know if a collider is added.
  4. Running the new component's Awake method.

This inspection will highlight calls to AddComponent inside a performance critical context. It will also mark the calling method as expensive, and any usages of the calling method will also receive a performance indicator highlight.

The inspection also adds Alt+Enter context actions to move the method call to Start or Awake, introducing a private field to cache the result. Please be aware that this can change the semantics of your code, as the component will be added at a different time.

This inspection was first added in Rider/ReSharper 2018.3

Clone this wiki locally