Skip to content

Instantly share code, notes, and snippets.

@qhwa
Created May 10, 2020 03:59
Show Gist options
  • Select an option

  • Save qhwa/5640a63b09aaa10bf8896da8f5a9e059 to your computer and use it in GitHub Desktop.

Select an option

Save qhwa/5640a63b09aaa10bf8896da8f5a9e059 to your computer and use it in GitHub Desktop.
sub-binary-and-match-context
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