Created
May 10, 2020 03:59
-
-
Save qhwa/5640a63b09aaa10bf8896da8f5a9e059 to your computer and use it in GitHub Desktop.
sub-binary-and-match-context
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
| defmodule MyBinParser1 do | |
| def valid?(<<length::2, data::binary>>), | |
| do: byte_size(data) >= length | |
| def valid?(_), do: false | |
| end | |
| defmodule MyBinParser2 do | |
| def valid?(<<length::2, _data::binary-size(length), _rest::binary>>), | |
| do: true | |
| def valid?(_), do: false | |
| end | |
| data = <<1000::2, :binary.copy("0", 1000)::binary>> | |
| Benchee.run(%{ | |
| mod_1: fn -> MyBinParser1.valid?(data) end, | |
| mod_2: fn -> MyBinParser2.valid?(data) end | |
| }) | |
| # `mod_1` is about 2.6x slower because it creates a sub-binary every time. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment