Reputation: 7
Cawas's GetOrAddComponent extension method (http://wiki.unity3d.com/index.php/GetOrAddComponent) has helped me a lot (in particular, how to create a generic method and introducing me to extension methods), but I'm curious as to how it would be more efficient than mine:
public static T GetOrAddComponent<T>(this GameObject obj) where T:Component
{
if(obj.GetComponent<T>() == null)
{
return obj.AddComponent<T>();
}
else
{
return obj.GetComponent<T>();
}
}
In my example, a variable isn't be created and stored in memory, so wouldn't that make mine more efficient? Or is there something I'm missing out on? (This is likely, I'm only a beginner :P)
Upvotes: 0
Views: 287
Reputation: 11452
The linked method makes one call to GetComponent
; the code you've pasted here makes two such calls. That's a big enough difference that it might show up under heavy load.
Depending on the compiler, comparing a local variable is negligibly different or not at all different from comparing an anonymous value. In the end, it's all being processed on the stack.
Upvotes: 1