I'm trying to understand how instance variables for a given object are stored for easy access later on.
For some background, I understand that if you have a reference to an array it is very easy for a computer to access any particular item in the array with an efficiency of $O(1)$ by just multiplying the index provided with the size of each item and adding that to the address of the array.
However it is not always meaningful to store things with just an index and so this is where things like HashMaps
can come in handy because they allow someone to store a particular value based on a key and retrieve it in the same $O(1)$ efficiency.
So now imagine that we have some class that has many many instance variables
class myClass {
int a1;
int a2;
int a3;
...
int a500; //or some other really big number
}
and I write some code such as
myObject is new instance of myClass;
myObject.a5 = 123;
myObject.a450 = 70;
//etc
So my questions is:
How does the the .a450
...etc get turned into an address? This type of access seems a lot more like the hashMap described above where a450 is a key that stores some corresponding value... however a hashMap really only attains that $O(1)$ access by careful maintenance of things such as the load factor. And to achieve the proper load factor you need to have a certain amount of empty items. There is also the issue that even though both hashMap and arrays have the same $O(1)$ access time... in practice the array will be much faster because there is no need to compute a hash function. It seems like this would not be an appropriate way to manage objects in any given language because if you have hundreds or thousands of such objects, then the overhead of having a hashmap would be very wasteful.