4 ms·
> a big array of objects for each index a flag whether the array element contains an object or not. Typically, you never need to iterate through all used objec
by Someone 3y ago
> a big array of objects for each index a flag whether the array element contains an object or not.
Typically, you never need to iterate through all used objects. Also, all unused objects are interchangeable from the program’s view. Each just is a chunk of memory that you can use to write a Foo to.
That leads to the standard way to do this for objects that are at least as large as a pointer: make the array an array of union{Foo, Foo*}, and, at allocation, create a linked list through all the unused entries. Getting memory for a new Foo then is just a matter of removing the head of the list, freeing a Foo a matter of appending it to the head of the list.
That means you don’t need n flags (one for each entry, but only a single Foo* pointing to the head of the free list. That’s a big gain if n is large.
(Doing that in Java is left as an exercise. It may not be possible)