get GetComponent speed boost

Thinking…

It has been brought up various times that getComponent is slow, but it doesn’t have to be THAT slow.
What makes it slow is that Unity is looping through your objects or scripts to find the one you specified.
Obviously, if the component you want is last in the search order each time, it is going to be slow, BUT I assume you can optimize getComponent with a little organization. If the component you were getting was first in the search order each time I would think there would be considerable speed boost.

Unity runs scripts in order from last to first on objects as they appear in the inspector window (when running from the editor at least). Does Unity getComponent search in the same order? I’ve done a few light tests that suggest this is the case, and I estimate you could get significant speed boosts on large scale projects if you keep components you must access (if you have an aversion to or a scenario that limits the use of faster access methods) organized in this manner.

BTW, it loops through objects from last to first in the editor also, but by the order you add them in. The hierarchy is listed in alphabetical order, so be aware of the difference.

Can anyone confirm this from knowledge or experience on a large scale or have insight into this? I would think you could get the speed close to a global variable if organized perfectly, but again my tests were light. I didn’t create a few hundred objects all with scripts on them or anything.

No, the speed increase is fairly trivial. In any case, the way to optimize it is to do GetComponent once, and store the result in a variable, which gives you a much bigger speed increase than ordering components. Also, GetComponent isn’t that slow to begin with (e.g., GameObject.Find is rather slower); you generally only bother to optimize it if you’re going to be doing it a lot.

–Eric

Thanks for the input.

I was getting a boost equivalent to a little better than 1/100th of a second by ordering components. A single global variable in the same test boost by a little better than 3/100ths. Storing as a variable is faster for your average situation, yes. And I agree with you that the differences might be considered trivial in average circumstances. In unusual or large scale circumstances, I can fathom it making a difference, but what that circumstance might be I don’t know.

I always found it to yield first-to-last. It’s obviously not reliable.