Why would one use
void *enif_alloc(size_t size) as opposed to
void *malloc(size_t size); when trying to allocate memory from an Erlang C NIF?
Reference does not specify much as to why.
http://www.erlang.org/doc/man/erl_nif.html#enif_alloc
I have seen NIF examples were malloc is used and I never see the enif_alloc. What does it do differently? Why is it better to use?
enif_alloc
uses the internal erlang memory allocators, which means that if the memory already is available in the internal VM cache it can use that memory instead of doing a system call to get the memory. This can lead to faster memory allocation in some cases, you will have to measure with your code to figure out if it makes any difference. In general I would recommend using enif_alloc
.
If I remember correctly using enif_alloc
also makes the memory used be included when issuing the erlang:memory
command.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With