GetComponent Makes 0.5K GC

There is a gameObject and a Script “B”,I want to use GetComponent,the Script “B” is not on the gameObject, so it will make 0.5k GC, how can I do?I want to judge if the gameObject has Script “B”.

This is only an issue when you run in the editor.

Running a built player? GetComponent will return null, as documented.

Running in the editor? GetComponent will allocate some memory to generate a special MissingComponentException with their “custom null” object.

Quoting a post from the Unity blog:

We do this in the editor only. 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.