[erlang-questions] bit syntax slower than bit operations

Bob Ippolito bob@REDACTED
Sat Sep 1 21:36:15 CEST 2007


On 9/1/07, Matthias Radestock <matthias@REDACTED> wrote:
> I stumbled upon some unexpected performance characteristics involving
> bit syntax. After some experimenting, I came up with the following
> example to illustrate the problem:
>
> Say I want to extract bits 2-5 of a single byte of binary data into a
> tuple, and also, conversely, construct a single byte of binary data from
> such a tuple:
>
> decode_compact(<<_:2, B5:1, B4:1, B3:1, B2:1,_:2>>) ->
>      {B2, B3, B4, B5}.
>
> encode_compact({B2, B3, B4, B5}) ->
>      <<0:2, B5:1, B4:1, B3:1, B2:1, 0:2>>.
>
> Code doesn't get much more compact than that.
>
>
> Now compare this against the following:
>
> decode_verbose(<<B:8>>) ->
>      {(B band 4) bsr 2, (B band 8) bsr 3, (B band 16) bsr 4, (B band 32)
> bsr 5}.
>
> encode_verbose({B2, B3, B4, B5}) ->
>      <<((B2 bsl 2) bor (B3 bsl 3) bor (B4 bsl 4) bor (B5 bsl 5)):8>>.
>
> Same result, but far more verbose.
>
>
> Unfortunately, my tests indicate that the latter version is about twice
> as fast, using R11B-5 under Linux on x86.
>
> Does the bit-syntax compilation produce rather inefficient code?

I don't know enough about the compiler or interpreter to answer your
question, but note that encode_verbose is not the same as
encode_compact. Consider any of B2 through B5 being integers outside
of 0 or 1. For a complete translation you'd need some extra (BN band
1) ops.

-bob



More information about the erlang-questions mailing list