Skip to content

Instantly share code, notes, and snippets.

@peburrows
Last active October 12, 2018 17:58
Show Gist options
  • Save peburrows/e22665d35bdfd4a7fc99e3d7d61e9cb0 to your computer and use it in GitHub Desktop.
Save peburrows/e22665d35bdfd4a7fc99e3d7d61e9cb0 to your computer and use it in GitHub Desktop.
defmodule Equality do
@tests [
0,
1,
-1,
2,
-2,
10,
-10,
3,
5,
8,
13,
21,
-3,
-5,
-8,
-13,
-21,
17,
19,
23,
29,
127,
128,
-127,
-128,
254,
255,
256,
384,
1_234_567_890,
-254,
-255,
-256,
-384,
-1_234_567_890,
987_654_321,
-987_654_321
]
def benchmark do
Benchee.run(%{
"primitive" => fn -> test!(&primitive/2) end,
"subtract" => fn -> test!(&subtract/2) end,
"pattern match" => fn -> test!(&pattern_match/2) end,
"match exception" => fn -> test!(&match_exception/2) end,
"exception" => fn -> test!(&exception/2) end
})
end
def test!(func) do
Enum.each(@tests, fn a ->
Enum.each(@tests, fn b ->
func.(a, b)
end)
end)
end
def primitive(a, b) do
a == b
end
def subtract(a, b) do
0 == a - b
end
def pattern_match(a, b) do
case a do
^b -> true
_ -> false
end
end
def match_exception(a, b) do
try do
^a = b
true
rescue
MatchError -> false
end
end
def exception(a, b) do
try do
1 / (a - b)
false
rescue
ArithmeticError -> true
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment