Lines of Code Formatting Performance?

I have a question regarding formatting lines of code. I see a lot of examples of code where a programmer has declared another variable of an already existing variable like this.

Renderer  r = GetComponent<Renderer>();

I assume this is done to make lines of code less lengthy and more readable. But to me this seems like an extra step. Are there any performance differences between r and GetComponent();?

Yes. GetComponent does work to find the component on the object, which has some cost. If you store it in r, then the finding is done only once and stored. Then it can be accessed very quickly any time.

GetComponent() is a method, that costs something to run. Much more than simply storing what it returns, in a variable and using that later.

That is why you will see many people save the result of get component in a variable during their Start or Awake methods, than using the result in the Update method.

More lines of code is not == to something costing more to run.

What about instances where a method is called only once? Like if I want a gameobject to rotate is just putting transform.Rotate(Vector3.forward); in update perfectly fine?

That’s not called once, though, it’s called every frame. If it’s actually called once (like in Start), then there’s no point caching the component.

–Eric