On my quest to creating 0 garbage when procedurally generating points I've stumbled upon a performance issue when comparing values to another values stored inside Dictionaries.
Initially I used lists and arrays but I recently revisited the code in order to avoid any garbage generation. Also I decided to use Dictionaries instead of Arrays/Lists because it seems useful to access a certain Key in a Dictionary.
I use Dictionaries in the following way:
- Each key is a mesh in my game
- Each value is an array of vertices or triangles
- Every array contains hundreds of vertices or triangles
Dictionary<int, Vector3[]> exampleVerticesDictionary;
Dictionary<int, int[]> exampleTrianglesDictionary;
My procedural system does the following:
1. Takes an initial random value (int or float).
2. Loops through all the items in the arrays of the 1st Dictionary.
3. If the value matches any value on any of the arrays, continue on the next loop.*
4. Loops through all the items in the arrays of the 2nd Dictionary.
5. If the initial value matches again, continue on next loop.
6. Loops through all the items in the arrays of the 3rd Dictionary.
7. If the initial value matches again, create a 3D point.
I access and compare items in Dictionaries in the following way:
if (exampleVerticesDictionary[key][index] == 1)
The problem: It causes noticeable performance spikes. The profiler indicates it's caused by the numerous calls (tens of thousands) to these methods:
Dictionary.get_Item()
GenericEqualityComparer.Equals()
Int32.Equals()
GenericEqualityComparer.Equals()
Int32.GetHashCode()
The questions:
- Why does the performance drop so much when using Dictionaries to make those comparisons?
- Am I just better off using Arrays of Arrays instead of Dictionaries of Arrays?
- Should I be using other way of accessing and comparing items in Dictionaries?
Thanks in advance! Coding is not my strong suit and I'm kinda lost with this issue...