#FindGameObjectsWithTag vs FindObjectsByType performance

1 messages · Page 1 of 1 (latest)

wind hill
#

I'm curious to know about the actual under the hood behavior of FindGameObjectsWithTag. I believe it could be faster than FindObjectsByType since Unity would already have a list of the GameObjects that are tagged and the untagged ones are already out. So less elements to iterate through.
I also read in the API doc that it retrieves an array of all active GameObjects tagged which tells me that it'll go through an array of just active GO.

So, am I wrong?

Note: I would only call this during the game's loading phase, not on every frame, so I'm not concerned of per frame performance, just the general behavior.

delicate prism
#

Allegedly the tags are at least indexed

#

Also note that FindObjectsByType goes through all UnityEngine objects not just GameObjects

wind hill
#

I'd love to know about the details but I just learnt something new. Got curious to benchmark.
Results were: There's no "best" method, It depends what you need. It's just wrong to compare these two since they aren't exactly the same.

FindGameObjectsWithTag is extremly fast if you just need GameObjects(and you can grab components later), while FindObjectsByType<T>() is better when you need direct access to specific MonoBehaviors.

I realized these two work really well together. For example use tag search for speed, type search when actually needed.

#

I tested on Unity with this setup(Note: I used chatgpt to help me build the benchmark scripts):
Generated a scene with lots of GameObjects, some tagged "House" / with House component
Compared tag-based vs type-based searches returning the same results
Ran each method multiple times (iterations) to reduce noise
Used Stopwatch to measure total + average time
Did a warmup run to avoid first-call overhead

Goal:
Find the fastest way to get houses from a realistic scene
Results:
🏠 House Lookup Benchmarks

FindGameObjectsWithTag -> GetComponent<House>
Found: 2000
Iterations: 500
Total Time: 108.8691 ms
Avg Time: 0.217738 ms
Scene Objects:10000
Houses: 2000

FindObjectsByType<House>(None)
Found: 2000
Iterations: 500
Total Time: 65.1378 ms
Avg Time: 0.130276 ms
Scene Objects:10000
Houses: 2000

FindGameObjectsWithTag
Found: 2000
Iterations: 500
Total Time: 15.4635 ms
Avg Time: 0.030927 ms
Scene Objects:10000
Houses: 2000

FindObjectsByType<GameObject>(None) -> CompareTag
Found: 2000
Iterations: 500
Total Time: 693.2209 ms
Avg Time: 1.386442 ms
Scene Objects:10000
Houses: 2000

iron hedge
#

Zero reason to ever use these method calls. If you care about performance you shouldn't just be loading these objects onto the scene without caching their references somewhere.

faint current
#

Yep. And the benchmark doesn't really reveal the full picture, as there could be a vast difference between the reported results and when you have a lot more tags defined in the project(depends on the implementation).