Search Unity

I'm regularly calling method on many GO's - store them in list or use FindGameObjectsWithTag?

Discussion in 'Scripting' started by Jimmy-P, Aug 17, 2019.

  1. Jimmy-P

    Jimmy-P

    Joined:
    Jul 10, 2014
    Posts:
    59
    So I instantiate a a few hundred gameobjects on game start, and I regularly call a method on all of them. As often as every 1 second. I'm currently using FindGameObjectsWithTag, but it occurs to me that I might as well just store them in a list when I instantiate them. I assume using a collection would be quicker since then I will already have the object reference, and using FindWithTag checks all objects in the scene.. but then I need to keep that list in memory. Thoughts? Anything I'm missing, should be aware of or should consider?
     
  2. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    9,443
    yes, keep those in array (or list), and the list can directly reference the script (if its same script that you reference in all of them), instead of array of gameobjects, and then doing getcomponent for the script.
     
    Jimmy-P likes this.
  3. Jimmy-P

    Jimmy-P

    Joined:
    Jul 10, 2014
    Posts:
    59
    Thank you! I hadn't even thought about the cost of using getcomponent, only finding with tag vs using object reference in list.
     
  4. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,338
    There's a few bits of info that you're missing.

    First of all, calling FindGameObjectsWithTag creates a new array in memory, every time. That means that you're spending the memory you'd spend on keeping it around every time you're calling that method. So you're not saving any memory at all by finding with tag - you're spending the same amount, just over and over again. The memory of the arrays you're done with will be reclaimed by the system eventually - this is called garbage collection, and it's a bit slow.

    So, setting aside the cost of searching through everything all the time, you're also using more memory, and you're spending a ton of time cleaning that memory back up.


    Also, before you start worrying about memory, you've gotta learn how much memory is spent on things.
    For example, a single (simple, uncompressed) 256x256 RGB texture in memory takes 1 byte per color, per pixel, so 3 bytes per pixel. That's 256x256x3 = 196608 bytes

    An array of references contains the size of the array (in a 4 byte int), as well as a pointer to each element it references. A pointer is 8 bytes if you're on a 64 bit system, or 4 bytes on a 32 bit system. If we assume you're not on ancient hardware, a 500 element array takes 4 + 500x8 = 4008 bytes. So, comparatively, your array is super-cheap.

    Which isn't to say that you should just allocate stuff willy-nilly. But, a simple array that you create once and then keep around while the game is running is really not going to be much of an issue.
     
    mgear, Yoreki and Jimmy-P like this.