The following code was used to get these results. I purposefully didn’t cache some of those components since I wanted to test how much time it takes to get them. For some of them, I did reuse the component to ensure everything was called the same number of times (at least on the surface as some of them call some of the others to get the job done).
for (int i = 0; i < 25000; i++)
{
GameObject thisGameObject = gameObject;
Transform myTransform = transform;
Vector3 myPosition = myTransform.position;
Quaternion myRotation = myTransform.rotation;
Rigidbody myRigidBody = rigidbody;
Vector3 myDirection = myTransform.forward;
int myLayer = thisGameObject.layer;
Renderer myRenderer = renderer;
Material myMaterial = myRenderer.material;
Color myColor = myMaterial.color;
}
Now some Components like (Transform, RigidBody, Material ) are easy to cache to avoid these costs since getting a reference to them works and from frame to frame, they don’t really change. However, others like transform.up / .forward / .position / .rotation (those we tend to check way more frequently sometimes each frame) and even if you had cached their transform are still going to hit you hard.
I realize that no one will loop through these like that but this does illustrate their relative cost to each other. So unless I am missing something here, is there any way to avoid some of those hits? Caching the transform of a component for which you may want to get the .forward of is good practice but that cost relative to using .forward is pretty small. For certain, within a pass / loop or whatever, I’ll be sure to create a local variable to hold myTransform.forward if i am going to use it more than once or any of these more costly .get_“something”.
I am relatively new to programming so I could be way off the deep end here so please enlighten me if I stayed wrong somewhere
P.S. I left out transform.tag … it’s a slightly more expensive than .position or .rotation plus it loves to bring GC.Collect with it … so compared to how inexpensive .layer is … I stay away from strings
Uploaded with ImageShack.us