Created
April 11, 2022 17:06
-
-
Save zmstone/1d8b71c2eec882dfa20b87269b3f1580 to your computer and use it in GitHub Desktop.
binary pattern match performance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| -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. |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you @kjellwinblad