[erlang-questions] bit syntax slower than bit operations
Matthias Radestock
matthias@REDACTED
Sat Sep 1 19:13:23 CEST 2007
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?
Matthias
More information about the erlang-questions
mailing list