Microsoft.Unity.Analyzers icon indicating copy to clipboard operation
Microsoft.Unity.Analyzers copied to clipboard

Cache expensive calls

Open jbevain opened this issue 5 years ago • 2 comments

It's generally recommended to cache the result of expensive calls like Camera.main and GetComponent inside the Start message and avoid calling them in Update/FixedUpdate.

Proposed solution

We should detect those calls, offer to cache the result and replace the invocations by the cached field.

jbevain avatar Feb 12 '20 18:02 jbevain

I would recommend putting the initialisation in Awake because it runs immediately when that script instance is created instead of Start which only runs before its first update.

Also, if it is possible to offer multiple different fix suggestions then it might be useful to have one for lazy initialisation rather than moving it to Awake:

private Rigidbody _Rigidbody;

private void Update()
{
    if (_Rigidbody == null)
        _Rigidbody = GetComponent<Rigidbody>();
}

SilentSin avatar Feb 26 '20 22:02 SilentSin

@SilentSin it's definitely possible to offer multiple suggestions for one diagnostic! I agree about using Awake instead of Start

jbevain avatar Mar 06 '20 17:03 jbevain