- Home /
Why is tag fast?
I heard that FindGameObjectWithTag is faster than GameObject.Find. But why? Although they both are strings, why are there performance differences in them?
Does tag work differently than name? I want to know why FindGameObjectWithTag is faster than GameObject.Find.
Answer by SmoothieTrash · Oct 10, 2021 at 05:52 PM
Hi @mon10lur49
Because not all gameobjects have a tag by default(they have Untagged as their tag)
therefore:
number of gameobjects with tag <= number of gameobjects
so it's faster
What you say is gameobjects with"Untagged" don't have tag variable as field? Then how does it work that comparing tag with gameobject with Untagged? Does Untagged means not only empty string, but also something?
They have, if you log it to console, you'll see a game object which is Untagged, prints Untagged. I guess that Unity has a list of GameObjects which stores gameobjects that don't have "Untagged" as tag value. Then when you call FindGameObjectWithTag, it does a linear search on that list.
Or maybe they have a Dictionary, with tags as keys, and List of GameObjects with that tag as their value (expect for Untagged gameobjects).
Either way I think it does a linear search.
Answer by Pangamini · Oct 10, 2021 at 03:44 PM
As far as I know, tag is not a string, really. That's why there's GameObject.CompareTag method. Tag is internally converted from string to some simple value
Ah, interesting. I thought it's because it's hashed, sort of like when dealing with animator or shader properties. But it seems like the benefit comes from the same idea
Right, we don't know the exact innerworkings. Since in order to use a tag it has to be defined in the tag manager could suggest that they actually do an index mapping of some sort. Though the other question was mainly about the performance difference between reading the tag property and using CompareTag.