Skip to content

Avoid usage of AddComponent in performance critical code

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

Invocation of AddComponent with MonoBehaviour as type parameter is costly, especially in performance critical context due to the following reasons:

  1. Finding the script in the cache by name or generating the cache object
  2. Allocating the required Monobehaviour memory
  3. Messaging and updating components
  4. Running awake code for new script.

This inspection will highlight invocation of AddComponent method in performance critical context with an Alt+Enter context action to move the invocation inside Awake or Start method and introduce private field which will store result of invocation inside class. This field will be substituted instead of each usages of AddComponent result

History:

  • This inspection was first added in Rider/ReSharper 2018.3
Clone this wiki locally