[erlang-questions] idea: service pack one

Bjorn Gustavsson bjorn@REDACTED
Thu Nov 15 07:53:26 CET 2007


"Juan Jose Comellas" <juanjo@REDACTED> writes:

> One thing that I was always doing when iterating over binaries is doing
> matches like the following one:
> 
> <<Head:Offset/binary, Char, Tail/binary>>

You don't have to do that anymore in R12B.

Take for instance your index/2 function:

index(Str, Char) when is_binary(Str), is_integer(Char) ->
    index(Str, Char, 0).
index(Str, _Char, N) when N > size(Str) ->
    0;
index(Str, Char, N) ->
    case Str of
        <<_Head:N/binary, Char, _Tail/binary>> ->
            N + 1;
        <<>> ->
            0;
        _ ->
            index(Str, Char, N + 1)
    end.

In R12B, you can write it simply like:

index(Str, Char) when is_binary(Str), is_integer(Char) ->
    index(Str, Char, 1).

index(<<Char,T/binary>>, Char, N) ->
    N;
index(<<_,T/binary>>, Char, N) ->
    index(T, Char, N+1);
index(<<>>, _, _) -> 0.

On my Sparc workstation this simpler program is more than twice as fast
in R12B.

Note: Your index function can be written speeded a bit.

index(Str, Char) when is_binary(Str), is_integer(Char) ->
    index(Str, Char, 0).
%% index(Str, _Char, N) when N > size(Str) ->
%%     0;
index(Str, Char, N) ->
    case Str of
        <<_Head:N/binary, Char, _Tail/binary>> ->
            N + 1;
        <<_Head:N/binary>> ->
            0;
        _ ->
            index(Str, Char, N + 1)
    end.

Still, even after this improvement, in R12B the simpler version is about twice
as fast.

/Bjorn
-- 
Björn Gustavsson, Erlang/OTP, Ericsson AB



More information about the erlang-questions mailing list