Does anyone know why this simple block of code is more efficient?

https://drive.google.com/file/d/1juVdnbzk1R2YhN0EgH7qmN50BwVdlx3n/view?usp=sharing, https://drive.google.com/file/d/1pQUBR9EK-aG15OhPrJuyBwCab4HEimfP/view?usp=sharing

The rider issues a warning, but the code works. I couldn’t understand why the other one was more efficient. I have basic knowledge and I am trying to improve myself. Thanks in advance.

I can’t upload code or image while uploading a question here. Can you help with this? :slight_smile:

Hello,

Its faster because you are caching transform inside a variable ( var transform1 = transform; ), in your slower example you are asking for transform basically three times, for example:

transform.position += transform.forward  * 10;
// is equal to
transform.position = transform.position + transform.forward  * 10;

You now clearly see that you are using transform 3 times, calling transform is doing some type of GetComponent<Tranform>() it is faster than normal GetComponent but it still takes time so its always good to cache components (and cache it once for example in Start function).

In short: When it comes to transform i would ignore this warning unless you are counting every nanoseconds of your CPU.