Hopefully this is not a duplicate.
Before anything, I know ArrayList are not the best choice but this is just curiosity.
Simply, I was wondering about the implementation of ArrayList. I looked and figured out it uses an array for storage.
For array, when you have:
int [] arr;
arr points to the first element of the array and because it is typed as integer, the compiler knows where to jump:
arr[2] => arr value + 2 * typeof(int) = address of arr[2]
Now, since ArrayList are typeless, I was wondering how the compiler can figure out where is the next item. I would guess there is an overhead that tells what is the data so that the compiler can perform the pointer arithmetic.
As a result, ArrayList should be way slower than any other typed collection since it cannot just jump to the data as it needs to know what is before. This would be quite similar to LinkedList.
An ArrayList
only contain references to the objects, not the objects themselves. All references are the same size, so the problem doesn't exist.
The internal type of the reference is surely object
.
For generic arrays of value types, the actual value is stored in the array and the size of the element is used as you describe. If you put a value type in an ArrayList
it will be boxed into an object and the reference to that object is stored in the ArrayList
.