comparetag vs getcomponent in raycast hit object

I read in this thread Do you use tags? and most people don’t like tags
and use components as tags

isn’t getcomponent() more performance expensive than comparetag, in a raycast context, cuz its in the update()?

GetComponent is more expensive than CompareTag (Slightly. It’s actually quite fast). There are other disadvantages of using CompareTag though:

  • Less compile/build time checking. If you change the name of a component class, but forget to update the GetComponent call, the GetComponent call will fail to compile, thus notifying you of your mistake. If you change the tag of a GameObject, but forget to update your CompareTag call, your code will just mysteriously stop working properly.
  • You can have any number of different components on an object, any of which you could check for with GetComponent. But with tags, each object can only have one. So if you have multiple things that need to raycast or collide with an object, and you want to look for two separate tags, you’re out of luck

In my experience, these disadvantages usually outweigh a slight performance advantage. The other thing is that often a CompareTag ends up being followed by a GetComponent anyway if you want to interact with the thing you hit in a meaningful way. This means you were going to take the performance hit of a GetComponent anyway, so you might as well use it to check if it’s the thing you care about and skip the CompareTag.

I wouldn’t say one or the other is strictly better. They’re different tools and each will be useful some of the time.

2 Likes

thanks:)

Just going to go all devil’s advocate for a bit… :wink:

If the majority of the things you hit aren’t what you care about hitting, then you may actually get a performance benefit from using CompareTag even though you may follow it with GetComponent. For example, you are shooting. You do a CompareTag checking if what you shot is an Enemy. If it is tagged Enemy then you will GetComponent for its health script. But the majority of shots will likely hit terrain or walls instead of objects tagged Enemy, and in those cases you don’t call GetComponent because you don’t change the health of the terrain. Especially if the game is heavy on inaccurate machine guns instead of sniper rifles. Just something to consider. Might be worth testing both approaches in the Profiler.

I also use CompareTag when I have multiple colliders on an object, and I need to do something different depending on which collider I hit, where GetComponent would make that more complicated. But this really isn’t the performance question from the OP.

1 Like

So basically… understand the differences between the two, understand the advantages and disadvantages of each approach, and choose one or the other depending on your specific use-case!

Above all, don’t fall into the trap of premature optimization. Most of the time you can just pick one and move on with your life.

1 Like