- Unity Game Optimization
- Dr. Davide Aversa Chris Dickinson
- 319字
- 2021-06-24 12:13:03
Using appropriate data structures
C# offers many different data structures in the System.Collections namespace and we shouldn't become too accustomed to using the same ones over and over again. A common performance problem in software development is making use of an inappropriate data structure for the problem we're trying to solve simply because it's convenient. The two most commonly used are perhaps lists (List<T>) and dictionaries (Dictionary<K,V>).
If we want to iterate through a set of objects, then a list is preferred, since it is effectively a dynamic array where the objects and/or references reside next to one another in memory, and therefore iteration causes minimal cache misses. Dictionaries are best used if two objects are associated with one another and we wish to acquire, insert, or remove these associations quickly. For example, we might associate a level number with a particular scene file, or an enum representing different body parts on a character, with Collider components for those body parts.
However, it's fairly common that we want a data structure that handles both scenarios; we want to quickly figure out which object maps to another, while also being able to iterate through the group. Typically, the developer of this system will use a dictionary and then iterate over it. However, this process is unfortunately very slow, compared to iterating over a list, since it must check every potential hash in the dictionary to iterate over it fully.
In these cases, it is often better to store data in both a list and a dictionary to better support this behavior. This will cost additional memory overhead to maintain multiple data structures, and insertion and deletion will require adding and removing objects from both data structures each time, but the benefits of iteration on the list (which tends to happen way more often) will be a stark contrast compared to iterating over a dictionary.