[erlang-questions] Binary pattern matching and optimization

Robert Virding rvirding@REDACTED
Mon Nov 24 20:10:38 CET 2008


2008/11/24 Vance Shipley <vances@REDACTED>

> I would like to have a function like this:
>
>        foo(<<_:Offset/binary, Foo:8, _/binary>>, Offset) ->
>                bar(Bin, Foo).
>
> Unfortunately that doesn't work:
>
>        Eshell V5.6.5  (abort with ^G)
>        1> compile:file(codec).
>        ./codec.erl:15: variable 'Offset' is unbound
>        error


The order in which arguments are matched is not defined so there is no
guarantee that Offset has a value when the binary is matched.

I don't understand why the first version can't work but
> neither do I understand much about writing compilers.
>
> So instead I do this:
>
>        foo(Bin, Offset) ->
>                <<_:Offset/binary, Foo:8, _/binary>> = Bin,
>                bar(Bin, Foo).
>
> This works fine of course but now I am trying to understand
> the meaning of this (optional) compiler warning:
>
>        Warning: INFO: using a matched out sub binary will prevent
>        delayed sub binary optimization
>
> How should I interpret this warning?


The compiler and VM is smart and optimises the matching of a binary where
the last segment is a binary. This makes it more efficient to use a binary
like a list and pick things off the front.

*BUT* for this to work the reference to the whole binary, Bin your case,
must not be used after the match, then the compiler can reuse that binary
reference and save work. You reuse Bin and the compiler is warning you that
when you do this it can't do a good a job as possible.

Robert
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20081124/4e255b83/attachment.htm>


More information about the erlang-questions mailing list