Skip to content

Instantly share code, notes, and snippets.

@ostinelli
Last active October 23, 2021 11:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ostinelli/b83da9a1a285d9be241ee22caec316fd to your computer and use it in GitHub Desktop.
Save ostinelli/b83da9a1a285d9be241ee22caec316fd to your computer and use it in GitHub Desktop.
Erlang delete double values in arrays (dict vs orddict vs sets vs ordsets vs maps vs gb_sets benchmark)
-module(list_bench).
-compile([export_all]).
main(Count) ->
Values = lists:foldl(fun(C, Acc) ->
[C, C, C, C, C, C, C, C, C, C | Acc]
end, [], lists:seq(1, Count)),
{TimeDict0, ResultDict} = timer:tc(?MODULE, count_dict, [Values]),
TimeDict = TimeDict0 / 1000000,
io:format("DICT (~p): ~p sec~n", [ResultDict, TimeDict]),
{TimeOrdDict0, ResultOrdDict} = timer:tc(?MODULE, count_orddict, [Values]),
TimeOrdDict = TimeOrdDict0 / 1000000,
io:format("ORDDICT (~p): ~p sec~n", [ResultOrdDict, TimeOrdDict]),
{TimeSets0, ResultSets} = timer:tc(?MODULE, count_sets, [Values]),
TimeSets = TimeSets0 / 1000000,
io:format("SETS (~p): ~p sec~n", [ResultSets, TimeSets]),
{TimeOrdSets0, ResultOrdSets} = timer:tc(?MODULE, count_ordsets, [Values]),
TimeOrdSets = TimeOrdSets0 / 1000000,
io:format("ORDSETS (~p): ~p sec~n", [ResultOrdSets, TimeOrdSets]),
{TimeMap0, ResultMap} = timer:tc(?MODULE, count_maps, [Values]),
TimeMap = TimeMap0 / 1000000,
io:format("MAP (~p): ~p sec~n", [ResultMap, TimeMap]),
{TimeGBSets0, ResultGBSets} = timer:tc(?MODULE, count_gb_sets, [Values]),
TimeGBSets = TimeGBSets0 / 1000000,
io:format("GB_SETS (~p): ~p sec~n", [ResultGBSets, TimeGBSets]).
count_dict(Values) ->
ValuesKV = lists:map(fun(V) -> {V, undefined} end, Values),
Dict = dict:from_list(ValuesKV),
dict:size(Dict).
count_orddict(Values) ->
ValuesKV = lists:map(fun(V) -> {V, undefined} end, Values),
Dict = orddict:from_list(ValuesKV),
orddict:size(Dict).
count_sets(Values) ->
Set = sets:from_list(Values),
sets:size(Set).
count_ordsets(Values) ->
Set = ordsets:from_list(Values),
ordsets:size(Set).
count_maps(Values) ->
Map = maps:from_keys(Values, undefined),
maps:size(Map).
count_gb_sets(Values) ->
GbSet = gb_sets:from_list(Values),
gb_sets:size(GbSet).
%% RESULTS for 1_000_000 (large list)
%%
%% 1> list_bench:main(1000000).
%% DICT (1000000): 430.271907 sec
%% ORDDICT (1000000): 1.912428 sec
%% SETS (1000000): 60.717392 sec
%% ORDSETS (1000000): 0.089105 sec
%% MAP (1000000): 2.994229 sec
%% GB_SETS (1000000): 0.127389 sec
%% RESULTS for 10_000_000 (dict and sets omitted)
%%
%% ORDDICT (10000000): 35.303066 sec
%% ORDSETS (10000000): 0.873909 sec
%% MAP (10000000): 38.187113 sec
%% GB_SETS (10000000): 1.528153 sec
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment