[erlang-questions] Warning: NOT OPTIMIZED: sub binary is used or returned

Björn Gustavsson <>
Tue Aug 7 08:24:05 CEST 2012

On Mon, Aug 6, 2012 at 6:36 PM, Zabrane Mickael <> wrote:
> Hi guys,
> I'm communicating with linked-in driver using the following code:
> control(Port, Command, Data) ->
>     case port_control(Port, Command, Data) of
>         <<0, Result/binary>> -> Result;                                           % <- LINE 468  handle a good case
>         <<1, Error/binary>>  -> {error, binary_to_term(Error)}    %  <- LINE 469  handle error case
>     end.
> When compiling, I got this 02 warnings:
> $ make
> Recompile: src/pimco.erl
> src/pimco.erl:468: Warning: NOT OPTIMIZED: sub binary is used or returned
> src/pimco.erl469: Warning: NOT OPTIMIZED: sub binary used by erlang:binary_to_term/1
> make[2]: Nothing to be done for `all'.
> Is there a way to get rid of these warnings and avoid a full binary copies?

Yes, you can get rid of the warnings by *not* using the bin_opt_info compiler

No, there is nothing to avoid here. The warning says that
a sub binary is created. A sub binary is small term that
references a part of a binary. Sub binaries is usually an
efficient way to reference just a part of a binary.

So there is *no* copying of the binary data going on in
your example.

The only time you have to worry about sub binaries
being created (and the reason for the optimizations
and compiler warnings) is when sub binaries are
being created repeatedly in a loop, for example in:

b2l(<<H,T/binary>>) ->
b2l(<<>>) ->

In this case, the compiler will optimize the generated
code to avoid creating a sub binary. Instead of
creating a new sub binary in every iteration of the loop,
a match context will be created once and kept through
the entire loop.

That will be beneficial in two ways:

1) Less garbage will be produced (by not building a
sub binary that will become garbage almost immediately).

2) Matching will be faster when the match context is
already available.

To summarize, don't worry about sub binaries
being created unless it happens repeatedly in a
tight loop.

Björn Gustavsson, Erlang/OTP, Ericsson AB

More information about the erlang-questions mailing list