Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

GetComponent("Component") is faster than GetComponent<Component()

Discussion in 'Scripting' started by ahSOLO1, Aug 24, 2021.

  1. ahSOLO1

    ahSOLO1

    Joined:
    Feb 1, 2020
    Posts:
    6
    Currently taking a Unity optimization course and I was told that
    GetComponent("Component")
    is faster than
    GetComponent<Component>()
    . I found this odd since the documentation says otherwise, but the profiler seems to agree with this view. Can anyone explain why this is the case?

    Here GC1 uses the generic version of the method and GC2 uses the string version. Each is called 5000 times in a for loop and the result is assigned to a variable. I've tried it with both Transform and Camera components, and in the latest LTS versions of Unity 2019 and 2020 with the result being the same.

    Code (CSharp):
    1.     void GC1()
    2.     {
    3.         temp = GetComponent<Camera>();
    4.     }
    5.  
    6.     void GC2()
    7.     {
    8.         temp = (Camera)GetComponent("Camera");
    9.     }


     
  2. diXime

    diXime

    Joined:
    Oct 2, 2018
    Posts:
    162
    Hello,
    that is surprising, but the data seems to not lie. Try to see if the length of the string type has a significant effect on this. Maybe GetComponent("string") is limited by the sequencial chars it is made of, so the difference may not be noticeable in short string such as "Camera".
    Now, the .02 ms of difference is not really of concern even for performance since you usually don't call GetComponent in Update. But that's still interesting.
     
    ahSOLO1 likes this.
  3. ahSOLO1

    ahSOLO1

    Joined:
    Feb 1, 2020
    Posts:
    6
    I think you're right. I tried getting the ParticleSystemForceField component instead and the times are now much closer together.

    upload_2021-8-23_17-11-35.png
     
    diXime likes this.
  4. diXime

    diXime

    Joined:
    Oct 2, 2018
    Posts:
    162
    Well, it seems that GetComponent("string") is still faster, because ParticleSystemForceField is longer than what I usually use (24 characters!). I'll take note on that. I wonder at what point the two meet to agree with the doc's recommendation (40 chars?).
    Thanks for the info !
     
    ahSOLO1 likes this.