[erlang-questions] Fast binary reverse
Thu Oct 27 10:46:05 CEST 2011
On 10/27/2011 10:12 AM, Ward Bekker wrote:
> I want to reverse the bytes of a bitstring as fast as possible. There is
> not a erlang BIF that does this, so I googled some possible solutions:
> Fun1 = fun(B) -> S = size(B)*8,<<X:S/integer-little>>=B,
> <<X:S/integer-big>> end.
> Fun2 = fun(B) ->
> binary:list_to_bin(lists:reverse(binary:bin_to_list(B))) end.
If you wrote those funs in the shell, they will always be interpreted by
erl_eval (not compiled to Beam code), which adds quite a lot of overhead
for such a small benchmark. The quick work done by the built-in
functions will be completely eclipsed by that overhead.
Note that funs in compiled code don't have much overhead - in that case
it's comparable to an ordinary function call. But for funs written in
the shell, you'll basically get a fun object that says "if someone calls
me, then call erl_eval to interpret this here abstract syntax tree and
return the result from the interpretation".
More information about the erlang-questions