I’m writing a quadtree-like data structure which contains matrices of generic objects T. If four subnodes all contain defined matrices of T, I’m going to aggregate them into a single, larger matrix, then delete the subnodes. Is there a more efficient way to do this than looping through every reference and copying it over? Can I copy chunks of memory instead?
Example:
T[,] _leaf1 = new T[64,64];
T[,] _leaf2 = new T[64,64];
T[,] _leaf3 = new T[64,64];
T[,] _leaf4 = new T[64,64];
// Populate leafs
T[,] _root = new T[128,128];
CopyInto(ref _root, ref _leaf1, 64, 64);
CopyInto(ref _root, ref _leaf2, 0, 64);
CopyInto(ref _root, ref _leaf3, 0, 0);
CopyInto(ref _root, ref _leaf4, 64, 0);
If you can make the structure immutable, you can perhaps save yourself from having to make lots of copies. Eric Lippert has some great posts about immutable structures.
Edit:
Again, I don’t know if it will improve performance in your case, but here is an example of a possible design with immutable objects:
Now you would be able to use it as follows:
Again, I don’t know if it is appropriate in your situation or whether it gives an performance improvement, because you have a level of indirection when getting the value. However, there are several ways to improve this, but it depends on what you really need to do.
Good luck.