Skip to content

Instantly share code, notes, and snippets.

@yowcow
Created November 21, 2019 07:10
Show Gist options
  • Save yowcow/786952fe2a32e6090521a65103babe18 to your computer and use it in GitHub Desktop.
Save yowcow/786952fe2a32e6090521a65103babe18 to your computer and use it in GitHub Desktop.
finding key existence in erlang
-module(bench).
-export([
run/0
]).
is_valid1(V) ->
V >= 1 andalso V =< 7.
-define(VALID_SET, sets:from_list([1, 2, 3, 4, 5, 6, 7])).
is_valid2(V) ->
sets:is_element(V, ?VALID_SET).
-define(VALID_MAP, #{
1 => true,
2 => true,
3 => true,
4 => true,
5 => true,
6 => true,
7 => true
}).
is_valid3(V) ->
maps:is_key(V, ?VALID_MAP).
-define(VALID_DICT, dict:from_list([
{1, true},
{2, true},
{3, true},
{4, true},
{5, true},
{6, true},
{7, true}
])).
is_valid4(V) ->
dict:is_key(V, ?VALID_DICT).
-define(VALID_PROPLIST, [
{1, true},
{2, true},
{3, true},
{4, true},
{5, true},
{6, true},
{7, true}
]).
is_valid5(K) ->
case lists:keyfind(K, 1, ?VALID_PROPLIST) of
{K, V} -> V;
_ -> false
end.
run() ->
Itr = 1000000,
erlang:display({is_valid1, timethis(fun is_valid1/1, 7, Itr)}),
erlang:display({is_valid2, timethis(fun is_valid2/1, 7, Itr)}),
erlang:display({is_valid3, timethis(fun is_valid3/1, 7, Itr)}),
erlang:display({is_valid4, timethis(fun is_valid4/1, 7, Itr)}),
erlang:display({is_valid5, timethis(fun is_valid5/1, 7, Itr)}),
ok.
timethis(F, A, Count) ->
timethis(F, A, Count, erlang:system_time(millisecond)).
timethis(_, _, 0, T0) ->
erlang:system_time(millisecond) - T0;
timethis(F, A, Count, T0) ->
F(A),
timethis(F, A, Count-1, T0).
@yowcow
Copy link
Author

yowcow commented Nov 21, 2019

13> c("bench").
{ok,bench}
14> bench:run().
{is_valid1,24}
{is_valid2,2175}
{is_valid3,31}
{is_valid4,2168}
{is_valid5,43}
ok

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