Last active
July 17, 2021 11:34
-
-
Save cheerfulstoic/e00bb6f451f4eed32e96fd481880a920 to your computer and use it in GitHub Desktop.
This file contains 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 Tester do | |
def update!(map) do | |
try do | |
{:ok, Map.update!(map, :blah, fn v -> v end)} | |
rescue | |
e in KeyError -> {:error, :no_key} | |
end | |
end | |
def update(map) do | |
{:ok, Map.update(map, :blah, %{a: 1}, fn v -> v end)} | |
end | |
def check_and_update!(map) do | |
if Map.has_key?(map, :blah) do | |
{:ok, Map.update!(map, :blah, fn v -> v end)} | |
else | |
{:error, :no_key} | |
end | |
end | |
end | |
with_key = %{:blah => 1} | |
without_key = %{} | |
Benchee.run(%{ | |
"check_and_update! - key exists" => fn -> Tester.check_and_update!(with_key) end, | |
"update! - key exists" => fn -> Tester.update!(with_key) end, | |
"update - key exists" => fn -> Tester.update(with_key) end, | |
"check_and_update! - key does not exist" => fn -> Tester.check_and_update!(without_key) end, | |
"update! - key does not exist" => fn -> Tester.update!(without_key) end, | |
"update - key does not exist" => fn -> Tester.update(without_key) end, | |
}) |
This file contains 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
Name ips average deviation median 99th % | |
check_and_update! - key does not exist 31.67 M 31.57 ns ±1173.96% 0 ns 990 ns | |
update - key does not exist 10.53 M 94.96 ns ±30972.53% 0 ns 990 ns | |
update - key exists 10.02 M 99.81 ns ±33800.81% 0 ns 990 ns | |
check_and_update! - key exists 9.98 M 100.18 ns ±26534.11% 0 ns 990 ns | |
update! - key exists 6.98 M 143.30 ns ±23903.76% 0 ns 990 ns | |
update! - key does not exist 1.60 M 625.12 ns ±1441.31% 990 ns 1990 ns | |
Comparison: | |
check_and_update! - key does not exist 31.67 M | |
update - key does not exist 10.53 M - 3.01x slower +63.38 ns | |
update - key exists 10.02 M - 3.16x slower +68.24 ns | |
check_and_update! - key exists 9.98 M - 3.17x slower +68.61 ns | |
update! - key exists 6.98 M - 4.54x slower +111.73 ns | |
update! - key does not exist 1.60 M - 19.80x slower +593.55 ns |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment