Skip to content

Instantly share code, notes, and snippets.

@zmstone
Created April 11, 2022 17:06
Show Gist options
  • Select an option

  • Save zmstone/1d8b71c2eec882dfa20b87269b3f1580 to your computer and use it in GitHub Desktop.

Select an option

Save zmstone/1d8b71c2eec882dfa20b87269b3f1580 to your computer and use it in GitHub Desktop.
binary pattern match performance
-module(bin_element).
-export([run/1]).
-define(CHUNK_SIZE, 1049).
run(Chunks) ->
BinL = [crypto:strong_rand_bytes(?CHUNK_SIZE) || _ <- lists:seq(1, Chunks)],
TotalBytes = ?CHUNK_SIZE * Chunks,
compare([hd(BinL) | BinL], TotalBytes).
compare(BinL, Bytes) ->
{T1, _} = timer:tc(fun() -> match(BinL, Bytes, <<>>) end),
{T2, _} = timer:tc(fun() -> sizer(BinL, Bytes, <<>>) end),
io:format(user, "match: ~p\n"
"sizer: ~p\n", [T1, T2]).
match([Bin | Rest], N, Acc) ->
case Acc of
<<Head:N/binary, _/binary>> ->
Head;
_ ->
match(Rest, N, <<Acc/binary, Bin/binary>>)
end.
sizer([Bin | Rest], N, Acc) ->
case size(Acc) >= N of
true ->
<<Head:N/binary, _/binary>> = Acc,
Head;
_ ->
sizer(Rest, N, <<Acc/binary, Bin/binary>>)
end.
@zmstone
Copy link
Author

zmstone commented Apr 13, 2022

Thank you @kjellwinblad

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment