[erlang-questions] Preallocated binary — save memory

Anthony Ramine <>
Wed Apr 10 18:29:28 CEST 2013


The following is an example of binary comprehension which is optimized to use a preallocated binary.

$ cat bc.erl
-module(bc).
-compile(export_all).
bc(Input) -> << <<0, 1, 2, Bin:42/binary>> || <<Bin:42/binary>> <= Input >>.
$ erlc +to_core bc.erl

Look at the generated bc.core file, you don't need to tweak the assembly directly as the mutable primops are introduced when compiling to Erlang Code.

Basically, it uses bs_init_writable instead of bs_init and bs_private_append instead of bs_append and if it can, it uses a sensible size for the initial buffer. You can see what these opcodes mean on Erlang on Xen's website [1].

Regards,

[1] http://erlangonxen.org/more/beam

-- 
Anthony Ramine

Le 10 avr. 2013 à 17:18, Max Lapshin a écrit :

> How can I reproduce that bs_init_writable?
> 
> I'm trying to make a smallest example of erlang code, make assembly out of it, try to change it and compile back.
> 
> Currently all my tests show that binary is reallocated.



More information about the erlang-questions mailing list