Why is myTransform = transform faster?


Transform myTransform = transform;

is apparently faster according to this: http://docs.unity3d.com/412/Documentation/ScriptReference/index.Performance_Optimization.html

Would anyone be able to explain why?

I hear that it is because it saves Unity having to look up the reference to the transform each frame, like:

Transform myTransform = GetComponent<Transform>();

but since:


is not a method and:


is a method, then transform should already be a field which is a pre-defined reference to the Transform on the given GameObject.


Transform myTransform = transform;

is surely redundant code?

That’s because when you access “transform” on it’s own, Unity is “conveniently” doing the GetComponent() call for you in the background. By setting it directly in a Start or Awake function, you only do the phantom GetComponent call that one time. Whether or not you really need to do that is dependent on how often you access the transform property. If you’re modifying transform.localPosition on every Update, for instance, you might want to cache your own myTransform. If you just modify it once in a while, it’s not that big of a performance concern.