Allocate Array of objects

I’d like to experiment with allocating objects in a sequential group vs fragmented objects with sequential algorithms.

What I have so far:

ary = Array(A).new(n)
ptr = Pointer(A).malloc(n)
n.times { ary <<; ptr += 1 }
# TODO: finalizer

How do I call initialize method? Is there a better way to do this?

The number is determined at runtime.

It’s just a method you call on the object, so .value.initialize.

To be honest this all sounds very YAGNI :D So I’m not sure about any better ways. FWIW Array is completely implemented in Crystal, there’s no compiler special casing for it beyond the literal syntax, so for example here’s the method to allocate a new array all pointing to the same value:

For the finalizer there’s GC.add_finalizer, though you probably want some kind of wrapper struct where you can iterate through the childrens to call finalize on them when the entire object goes out of scope.


Error: protected method 'initialize' called for A, obj) works for Struct, but not Object. The same object reference occupies all slots.

Yes, I didn’t mean to say it’s equivalent, just similar.

Well I guess you want to make a public method on A or Object then that calls initialize.

Right now I’m at the benchmark stage. If it don’t see a signifiant improvement I’ll toss it.