BAR
BAR

Reputation: 17111

Erlang binary matching efficiency

What would be the difference between matching like:

fun(Binary) ->
    [Value, Rest] = binary:split(Binary, <<101>>)
end

and

fun(Binary) ->
    [Value, <<Rest/binary>>] = binary:split(Binary, <<101>>)
end

I am thinking that one may simply increment a counter as it traverses the binary and keep the sub binary pointer and the other will copy a new binary. Any ideas?

Upvotes: 0

Views: 551

Answers (2)

allenhwkim
allenhwkim

Reputation: 27738

I can think of pattern matching in two ways.

Method 1:

[A,B] = [<<"abcd">>,<<"fghi">>] 

Method 2:

[A, <<B/binary>>] = [<<"abcd">>,<<"fghi">>]

Unless you need to make it sure B is binary, Method 2 will take it longer, few micro seconds, because it's not just assigning <<"fghi">> to B, but also make it sure it is bianary.

However if you need more parsing than method 2, you can go further, which method 1 can't do.

[A, <<B:8, Rest/binary>>] = [<<"abcd">>,<<"fghi">>].

Upvotes: 1

Chen Yu
Chen Yu

Reputation: 4077

I think you could test it by timer module's tc/N function.

Upvotes: 1

Related Questions