What is the performance of .gameObject?

can I use .gameObject freely within a monobehaviour to access the game object it is attached to or should I reference it once and use the reference afterwards?

I ask this because there are some methods like .getcomponent and object.find that have such bad performance that they should only be called once to save them to a reference and then use the reference thereafter.

So the question is: can I use .gameObject freely or is it similar to getcomponent performance wise and should I use it only once to create a reference?

Thanks!

I don’t think things like ‘GetComponent’ or ‘.gameobject’ really relate to ‘.find’. Though the first two are slightly slower then having a reference directly it will not be as slow as ‘.find’ and wont create garbage like ‘.find’.

I think that since 5.0 (I might be wrong) they automatically cache certain Monobehaviour variables. I took the habit of caching transform to a private variable but I freely use .gameObject pretty much everywhere and I never had an issue.

Of course calling it 4000 times per Update might become an issue.

If you know you’re going to reuse that variable a lot then it’s worth using the 4bytes of memory for the reference.

1 Like

I would certainly not lump GetComponent together with GameObject.Find(). GetComponent can be called thousands of times per frame with no perceptible performance impact.

The .gameObject property is likely even better than that. While its implementation is not really known, I can’t imagine it’s much worse than a hashtable lookup.

If you’re approaching this from the angle of “hey I heard this is bad…” Instead of “I profiled my game and noticed this is bad” you’re probably prematurely optimizing.

2 Likes

At risk of going on a tangent, I’ve seen performance issues calling GetComponent a few dozen times in Start during prefab instantiation. Most prominently the first time the prefab has been instantiated. I’ve also seen GetComponent called hundreds of times per frame in Update without causing any significant performance issues. I would have investigated this further, but replacing GetComponent calls in Start with inspector references resolves the issue, and I tend to move on when a problem gets solved rather than go down the rabbit hole of further investigation :stuck_out_tongue:

On the original question, I’ve never seen the profiler point to any of my code using .gameObject, and I use it quite frequently. I’d suggest just using it and only doing potentially better optimization if it actually does become a problem.

2 Likes