Performance of Unity methods

In my spare time I like to think of ways to program better in Unity. Most of the time that thought goes way beyond what you will ever need in a practical developement cycle.

In the last few days I was curious how fast (or slow) those methods we call all the time (and maybe shouldn't) actually are. This thought came from a post that said GetComponent was as bad as GameObject.Find(). I couldn't believe that so I started testing. What I eventually tested was:

  1. this.GetComponent<Test>()
  2. this.AddStuff<float>(t)
  3. this.AddSomething(t)
  4. this.gameObject.transform
  5. Time.deltaTime
  6. this.gameobject
  7. Input.GetKeyDown(Keycode.A)
  8. GameObject.Find(this.name)

As I suspected both method vary widely.
My test consisted of 5 GameObjects in the scene where one had one child. Thes test ran for 1300 frames with a starting offset of 200 frames (so that the startup will not affect the times). Each frame the tests were executed 20.000 times and timed with Stopwatch().

I tested this on a Mac Mini (Sierra) with a 2,3 GHz Intel Core i7 and 8GB of memory. For graphics it has an Intel HD Graphics 4000 (1536 MB) integrated.

So GameObject.Find is definately worse :)
I did not expect to have a difference so high with only 6 GameObjects in the scene.

Because GameObject.Find is so slow I excluded it from the rest of the results.
The rest for me is way more interesting:

This shows that clearly you should try not to use GetComponent very often. With that said, even if you would call GetComponent 1.000 times, on average, you will loose only about 0,7 ms.

Given that you would need 20 thousand calls to have an effect of around a half a millisecond in most cases, I think you can ignore the cost of calls to transform or even GetKeyDown. If you have thousands of GameObjects that call Input.GetKeyDown you probably have bigger problems.

Generally there are always bottelnecks that will probably weigh way harder than GetComponent.
For your own verification, at the bottom is the code of the complete test. Here is the excel file with all the raw data down below so you can make your own fancy graphs :)

I thought this was it. Simple tests but they showed nothing really new.
A few weeks later someone asked me if they could easily check 200 vectors in a loop. I knew they were making an app that had to support at least the Ipad Mini 1 or equal. So I thought: Let's test it!
And it got interesting...

As you can see GameObject.Find() is even worse with an average caculation time on Ipad Mini 1 of 68 ms! That means in one millisecond you can only search about 145 times and thats it! But more importantly: Look at the IPhone 7's results in this.Getcomponent():

They are even a little bit higher than GameObject.Find().

Here are the other images I took leaving out GameObject.Find and then this.Getcomponent().