Does GetComponent<T> no longer allocates garbage?

I’m noticing that calls to GetComponent don’t show any garbage allocations in the profiler, I’ve seen several articles/tutorials mentioning that calling GetComponent was an expensive operation due to garbage allocations, was this patched recently and is no longer the case?

For reference I’m using Unity 2020.1.6f1 with Mono scripting backend.

Here is a snippet of my code:

        private void PushActors(Vector2 direction, float distance)
        {
            foreach (RaycastHit2D hit in CastAll(direction, distance, actorsMask))
            {
                Actor actor = hit.transform.GetComponent<Actor>();

                // Do stuff...
            }
        }

It never allocated garbage at runtime. What happened was that in the editor only, if there wasn’t any T attached to that gameObject, an “error object” was allocated to give better error messages. This causes the error you get when you try to use the thing returned to be “there’s no T attached to the gameObject” rather than “NullReferenceException”.

That’s probably not been removed, but I’m pretty sure that it’s been on the profiler team’s roadmap to strip out some editor-only allocations, to help understand what’s going on better.

3 Likes

I see, so garbage allocation was never an issue at runtime then, striping out editor-only allocations from the profiler sounds like a good idea to avoid confusions.

Thanks for the explanation!

You are partially right :wink:
We did have this on our roadmap but have implemented this since and are excluding them to contribute to parent samples in hierarchy view. Not 100% sure anymore since which version but if your Hierarchy view toolbar has an option button in the top right hand corner, it’s getting filtered out. You can toggle that behavior in this options drop down.

1 Like

Alternatively, using TryGetComponent do not allocate in editor.
And its most likely API to use for the most cases.

1 Like