ArrayLists or Tags?

Generally speaking, is it quicker to get objects via their tags or from an array (ArrayList)?


var apples = GetComponent("FruitBasket").apples;
for (var a : GameObject in apples)
//eat apple or something


for (var a in GameObject.FindGameObjectsWithTag("apple"))
//eat apple or somthing


The difference in what you're doing should be unnoticeable. It would only start to matter if you were calling FindGameObjectsWithTag or GetComponent in a loop. Do whatever's easier.

However, this is slow:


Do this instead:


All that said, GetComponent is likely faster than FindGameObjectsWithTag, and GetComponent is easier to deal with, because it doesn't have to deal with a string. Strings, in this case, don't generate helpful errors at compile-time. The fastest possible thing would be to store a reference to the FruitBasket component, and not call GetComponent on it at runtime, but you're never going to notice this performance increase. Only store that reference if you're going to use it a lot.


You can use the script's drop-down menu, in the Inspector, to call CacheReferences, or you could call the function from code, whenever you want. You can set up as many variables as you like, with the function, hence the name I gave it. Add to it if it would be helpful.

var fruitBasket : FruitBasket;

@ ContextMenu ("Cache References")
function CacheReferences () {
    fruitBasket = GetComponent.<FruitBasket>();

function EatApplesOrSomething () {
    for (var apple in fruitBasket.apples) {
        //eat apple or something