CompareTag()

Arakade

New member
Hey

I learnt recently about `GameObject.CompareTag()` when Rider suggested it had better performance than a "explicit string comparison". I'm not sure of difference to use of `string.Equals()` but see this answers question for some notes indicating it allocates!

I noticed `HasEnteredTrigger` line 28 (and all the accompanying Collision Actions, etc) currently use `tag.Value.Equals(other.gameObject.tag)`. Is there merit in converting these?

Thx
 
Whenever you use a string it is going to cause some allocations, which is why I prefer not to use tags at all. I will change it to compare tag though :)
 
Whenever you use a string it is going to cause some allocations

That's intriguing -- just due to being a reference type or are there string specific gotchas. (I'm not a big use of strings or tags but still good to know.)

Thx
 
Strings are a class so when you do something like "MyString" it is the equilivant of doing a new String(). The allocations are pretty minor but the bigger thing is comparing them - string comparisons are slow because you have to compare each character. It's much quicker to compare other types of objects.
 
heh, ok thx. But no extra allocations in a comparison? ...

I found the idea that string equality checking would cause allocations unexpected in the obvious case -- both already in managed heap. The impression I got from that reference was that `gameObject.tag` retrieves a new copy of the C++ string and allocates it into the managed heap hence the allocation. Understood. However I was concerned I might be missing something subtle about how a C# string comparison works? E.g. could one of the `StringComparison` values (maybe other than `Ordinal`) be (crazily) allocating the converted string rather than doing an on-the-fly value-type comparison. I'd hazard the reason `CompareTag()` might be faster is that it might be optimised by knowing the potential tag values in advance (e.g. hash them into a Dictionary so a compare is just 1 hash + lookup).

Anyway, I come from a C and Java background and despite having worked in Unity C# for a few years now, I am aware that there might be stuff all C#-natives know that I might assume otherwise hence needing to pull any threads that seem counterintuitive to my expectations :D

Thx again
 
Top