I’m working on a game, and to be on the safe side any user (programmer) is only allowed to store IDs to objects instead of pointers, and must use this ID to get the pointer to the object in order to have to some quality alone-time with it.
Let’s use the worst case scenario: Every single ID is in use. It is 64 bit so there ya go: 18446744073709551616 IDs to search through. A lot of the data is stored in a database, and our program lookup either returns a pointer, or a null pointer. A null pointer means the program must access the database in order to load the object, after which it will have a pointer.
Ideas:
So the only real trick I know here is binary search. So in the worst case that means 64 comparisons for every ID lookup.
Another idea I had was creating a static space partition, a tree where every branch splits up into a power of 2 amount of branches, but only until a reasonable depth. Using a bitwise operator on the ID instead of the modulus operator to find out what branch it belongs to on every level. Every possible branch in the tree always exists, but at some depth they stop and a binary search is still required because the exact number of values is still unknown.
What are your ideas?
This is a classical case for a hash map. First, realize how many IDs you can actually have active at any one time. 2^64 is nonsense since then even the data structure just to hold these IDs and the pointers to the objects would already be at least 268’435’456 TB. Now, there’s nothing wrong with using 64bit IDs, but figure out how many objects you will have active at any one time, choose a reasonable number like say 5’000 and use a hash map of say 10 times the number of objects. If your load factor is low enough and your hash function good enough you will get an amortized O(1) access time.