Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use enif_alloc instead of malloc

Tags:

c

malloc

erlang

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?

like image 950
BAR Avatar asked Dec 12 '22 18:12

BAR


1 Answers

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.

like image 138
Lukas Avatar answered Dec 17 '22 20:12

Lukas