Storage of children references efficiency

Hello,

I have large objects with different types of child components. When certain events happen, certain types of the children need to be modified.

Is it better to “get” and store all of the different types of children in the beginning or “get” them every time a script is run?

Example of storing children in the beginning, then accessing them later:

public A[] allA;
public B[] allB;
public C[] allC;

void Start(){
   allA=GetComponentsInChildren<A>();
   allB=GetComponentsInChildren<B>();
   allC=GetComponentsInChildren<C>();
}

public void doStuffWithA(){
   foreach(A a in allA){ a.doStuff(); }
}

public void doStuffWithB(){
   foreach(B b in allB){ b.doStuff(); }
}

public void doStuffWithC(){
   foreach(C c in allC){ c.doStuff(); }
}

Example of “getting” children every time it does stuff:

public void doStuffWithA(){
   A[] allA=GetComponentsInChildren<A>();
   foreach(A a in allA){ a.doStuff(); }
}

public void doStuffWithB(){
   B[] allB=GetComponentsInChildren<B>();
   foreach(B b in allB){ b.doStuff(); }
}

public void doStuffWithC(){
   allC=GetComponentsInChildren<C>();
   foreach(C c in allC){ c.doStuff(); }
}

Per-tick lag is an issue in this game. Graphics and memory are less so.

These scripts are run every 5 seconds on average.

Thanks,

Nomenokes

As long as the children do not change the first way is of course the preferred one. However when you add / remove children dynamically at runtime the first one of course doesn’t work.

Running GetComponentsInChildren once every 5 seconds really isn’t that much. However the method itself of course has some processing overhead. The more child objects and components there are, the slower the method gets. Also since the method returns an array it will allocate garbage which will cause the garbage collector to kick in from time to time. You can’t really avoid garbage generation, though depending on the target platform you generally want to keep it low.