- Home /
Unityscript - Which GetComponent is faster ?
Here are two versions of GetComponent in Unityscript
Here's one..
private var brain:BrainScript;
brain = head.GetComponent(BrainScript);
And here's the other, the Generic ..
private var brain:BrainScript;
brain = head.GetComponent.<BrainScript>();
Does anyone know: is one faster than the other?
(Note .. you can also I believe use GetComponent by passing it a string. So, GetComponent("BrainScript") would also work. If you do that, it is very slow. Generally one would never do that. I'm not asking about that. I'm asking about the two variations above where you pass in the type.)
Does anyone know if there's any speed difference, or indeed any difference at all, between the two?
Cheers!
I don't know - but I think that they are exactly the same. GetComponent(BLAH) is effectively using the generic I believe but it avoids the beginner unfriendly syntax.
@yusolaifdfer: the generic version of GetComponent has a performance penalty, both in C# and Unityscript. Furthermore, a generic List is slower than a built-in array of the same type, by quite a lot in the case of primitive types. Generics are only faster when compared to something like ArrayList, which requires boxing/unboxing.
@whydoidoit: GetComponent(Blah)
is effectively doing GetComponent(Blah) as Blah
, not the generic version, which as demonstrated by Gerry$$anonymous$$ (and mentioned by myself on many occasions ;) ) is a little slower.
Answer by GerryM · Apr 04, 2013 at 11:05 AM
Interesting, after testing it with this script, it seems the first version is slightly faster (about 1.4) than the second version (about 1.7). You might want to check for yourself in your specific setting, though.
function Start () {
var sw = new System.Diagnostics.Stopwatch();
sw.Start();
for (var i = 0; i < 10000000; i++)
{
var brain = GetComponent(BrainScript); // Version 1
//var brain = GetComponent.<BrainScript>(); // Version 2
}
sw.Stop();
Debug.Log("Elapsed = "+sw.Elapsed);
}
holy testing, batman ! that's amazing..
BTW System.Diagnostics.Stopwatch(); incredible tip, thanks
Your answer
