Jacob M. Barnard
Jacob M. Barnard

Reputation: 1367

Are Hashes ever on the stack in Crystal lang?

In the Crystal language, are Hashes ever allocated on the stack? Or are they always 'heaped'? I could not find anything in the docs (https://crystal-lang.org/api/0.33.0/Hash.html - looked up on 19 Feb 2020). I see quite a few malloc_* in https://github.com/crystal-lang/crystal/blob/master/src/hash.cr, but wasn't sure if there was optimization I was missing. I don't think the docs call it out explicitly - did a word-find in browser for 'heap', 'stack' and 'allocate' on https://crystal-lang.org/api/0.33.0/Hash.html... couldn't find anything.

Upvotes: 2

Views: 156

Answers (1)

Philipp Claßen
Philipp Claßen

Reputation: 43999

Hashes are always heap allocated.

In Crystal, it depends on whether a object is of type Reference or Value. All objects that inherit from Reference are always allocated on the heap.

A hash is defined as class Hash(K, V). As class always inherits from Reference, hashes will always be heap allocated.

Value types like struct Int32, where stack allocation is desirable, have to be defined as structs, so they do not inherit from Reference but from Value.

Upvotes: 2

Related Questions