Created
November 21, 2019 07:10
-
-
Save yowcow/786952fe2a32e6090521a65103babe18 to your computer and use it in GitHub Desktop.
finding key existence in erlang
This file contains hidden or 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
-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). |
Author
yowcow
commented
Nov 21, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment