Skip to content

Instantly share code, notes, and snippets.

@cararemixed
Created July 2, 2019 17:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cararemixed/8292f030e134ee7d985a08a7d87d8c66 to your computer and use it in GitHub Desktop.
Save cararemixed/8292f030e134ee7d985a08a7d87d8c66 to your computer and use it in GitHub Desktop.
# Using the benchee library
keys =
1..12
|> Enum.map(fn key ->
Integer.to_string(key)
end)
map =
keys
|> Enum.take_random(9)
|> Map.new(&{&1, true})
times = 100_000
# NOTE: The benchmark loops return :ok to explicitly
# avoid generating lists as garbage (the Erlang
# compiler will turn that into a loop and avoid
# generating a list entirely).
Benchee.run(%{
# Enable this to compare the loop overhead itself
# "null" => fn ->
# for _key <- keys, _ <- 1..times, do: :ok
# :ok
# end,
"Map.get" => fn ->
for key <- keys, _ <- 1..times do
Map.get(map, key)
end
:ok
end,
"Access" => fn ->
for key <- keys, _ <- 1..times do
map[key]
end
:ok
end
})
@cararemixed
Copy link
Author

Sample results:

Name              ips        average  deviation         median         99th %
Map.get         11.19       89.37 ms     8.63%       94.00 ms      110.00 ms
Access           9.88      101.24 ms     8.40%       94.00 ms      125.00 ms

Comparison:
Map.get         11.19
Access           9.88 - 1.13x slower +11.87 ms

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