Lam Cao's Blog

A Journey in Game Dev

[Unity Tips] Use CompareTag instead of string.Equals

Comparing tags is a thing we all do in every game project at some point but not everyone seems to know about the existence of CompareTag. Unity could really have done a better job documenting this useful method.

In short, use obj.CompareTag("someTag") instead of string comparisions such as obj.tag=="someTag". CompareTag is much faster and will log an error if a tag is not defined, which is a very good thing.

In case of comparing against a list, use list.FirstOrDefault(t=>obj.CompareTag(t))!=null rather than something like list.Contains(obj.tag) for the same reasons.

It turns out that tag causes a heap allocation for every access, which is obviously a waste of both processing time and memory. It is believed that CompareTag uses internal engine methods rather than C# strings to get the job done which prevents unnecessary memory allocation.

I did a quick simple test to get an idea of how much faster CompareTag is compared to other C# string equality methods. The code below can be inserted into Start or OnMouseDown method (or whatever) to test.

if (UseCompareTag) 
    for (int i = 0; i < N; i++) 
        if (CompareTag("Player")) {} 
    for (int i = 0; i < N; i++) 
        if (tag == "Player") {} 

For N = 10k, == operator takes about 3.5ms to finish while CompareTag takes only 1.4ms! (The overhead is minimal) The difference is even larger for big Ns. Even if “there ain’t that many tag comparisons at any given time”, it is always beneficial to follow best practices in the first place.

The second huge benefit of using CompareTag is error checking. The tag you are comparing against needs to be defined in the Tag list, otherwise, an error will be thrown. == simply returns false even for unknown tags. I can’t tell how much time I have wasted because of silly misspelled strings. Error is a good thing in this case and will save us a lot of time!

Hope you find this useful.

Leave a Reply

Your email address will not be published. Required fields are marked *