Should GetComponent() generate garbage when the component is not found?

We were profiling (deep profile) our game to check about cpu and garbage generation when we found out that GetComponent() was generating garbage in some cases. After making some tests we discovered that it was when the component is not found and GetComponent() returns null.

We created a test project to replicate this bug in order to easily share it with you.

The project consists of two scenes:

  • GarbageTestCaseScene - it has a GameObject with a component/behaviour calling GetComponent() multiple times per update while the asked component is missing.
  • NoGarbageTestCaseScene - it has the same component/behaviour but it asks for a component that exists on that GameObject.

To replicate the bug run the first scene and start profiling and you will see that a lot of garbage per frame is generated while on the other scene this doesn’t happen.

This is the code of our behaviour calling GetComponent():

public class GetComponentBehaviour : MonoBehaviour
	void Update()
		for (int i = 0; i < 5000; i++) {
			AnotherBehaviour component = this.GetComponent<AnotherBehaviour>();

The question is, should this be happening? Why? We know it is not recommended to call GetComponent multiple times per update but we need it in some cases and we are willing to pay the CPU cost but not the garbage generation one.

The test cases were tested using Unity 4.3.4f1 pro and 4.3.2f1 free.

UPDATE: in case anyone wants to know, the issue case is 590565.

Oh, just read this post, it says:

This is why when you call
GetComponent() to query for a
component that doesn’t exist, that you
see a C# memory allocation happening,
because we are generating this custom
warning string inside the newly
allocated fake null object. This
memory allocation does not happen in
built games. This is a very good
example why if you are profiling your
game, you should always profile the
actual standalone player or mobile
player, and not profile the editor,
since we do a lot of extra security /
safety / usage checks in the editor to
make your life easier, at the expense
of some performance. When profiling
for performance and memory
allocations, never profile the editor,
always profile the built game.

Seems like the null we see isn’t really null, and it isn’t generating garbage in built games. I guess I don’t have to worry anymore then.