Skip to content

Instantly share code, notes, and snippets.

@Awlexus
Created November 28, 2019 23:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Awlexus/68f39ed506d81bd93ea7f36ace26bfc8 to your computer and use it in GitHub Desktop.
Save Awlexus/68f39ed506d81bd93ea7f36ace26bfc8 to your computer and use it in GitHub Desktop.
A small benchmark comparing different implementations of a possible pop_by functionality
# Keyboard mashing
tags = ~w(faoshd foasidf oasidfh oaidsf aosifhasodi faosdfaosdfasodfjasldfd noasdfn 1234234 oasdinf oasnfoasdifnoisdfnof)
defmodule Popper do
def pop_by(list, fun, default \\ nil) do
result = Enum.find(list, default, fun)
{result, List.delete(list, result)}
end
def pop_by2(list, fun, default \\ nil) do
case Enum.split_with(list, fun) do
{[result], other} -> {result, other}
{[], other} -> {default, other}
end
end
def pop_by3(list, fun, default \\ nil) do
{result, others} =
:lists.foldr(fn
tag, {nil, acc} ->
if fun.(tag) do
{tag, acc}
else
{nil, [tag | acc]}
end
tag, {found, acc} ->
{found, [tag | acc]}
end, {nil, []}, list)
{result || default, others}
end
def integer_string?(str) do
match?({i, _} when is_integer(i), Integer.parse(str))
end
end
# Save some writing
# Tries to find a string that can be parsed from a list and return 720 by default
simple_fun = fn fun ->
fn -> fun.(tags, &Popper.integer_string?/1, 720) end
end
Benchee.run(
%{
"find & delete" => simple_fun.(&Popper.pop_by/3),
"split_with" => simple_fun.(&Popper.pop_by2/3),
"foldr" => simple_fun.(&Popper.pop_by3/3)
},
time: 10,
memory_time: 2
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment