Group or array

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Gary_CHAN

I have a game which will have at worst 1000+ objects at the same time with different properties. I would like to call a method (which is just a simple action like changing position or changing a variable in script) on each of them if they have the same properties.
I have two methods in mind:

  1. add them to a group if they have same properties and use get_tree().call_group(…)
  2. add them to an array if they have same properties and iterate over the array to find the object and call method on it.
    I would like to ask:
    if at worst I need to create 1000+ groups/array and each of them contains 1000+ members, which method is better/ faster approach ? Will it slow down the game if I have thousands of groups and lots of members in each group?
:bust_in_silhouette: Reply From: Zylann

The best way is to try.

In terms of data structure, a way to represent this situation is a dictionary of arrays, which is what groups are. Although, I feel groups were designed for you to know them in advance, but I doubt it if you can have 1000+ of them :stuck_out_tongue: They would still technically work and I think in GDScript the result might be the same, but it’s probably an extreme usage if you have other groups to worry about which are not related to that system.

Performance will depend on how often this changes, and how addition, removal and iteration is done. For example, a removal which shifts all following elements is slower than an unordered removal which only swaps the last element to replace the old one.
Due to this, you might also consider dictionary of dictionary, or array of arrays (by using indexes instead of group names).

Also maybe another way is to not use groups at all (or partially), and simply iterate over them all and do the thing you need to do by checking properties dynamically, without bothering to maintain a “database”. But without knowing what you are actually doing, it’s not easy to find if it’s relevant.

Thank you. I will try to test different methods.

Gary_CHAN | 2019-07-30 13:02