-
Notifications
You must be signed in to change notification settings - Fork 134
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:
- Finding the component's script in the script cache, by name. This might also incur allocations if it's not already cached.
- Allocating the memory for the
MonoBehaviour
. - 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.
- 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