我发现“功能 ets:select/2 和 mnesia:select/3 应该优先于 ets:match/2、ets:match_object/2 和 mnesia:match_object/3”表单参考链接:http://www.erlang .org/doc/efficiency_guide/tablesDatabases.html
而且我读过一些关于选择和匹配之间比较的文章,我得出结论有一些因素会影响结果,例如表中的记录数量,是否选择/匹配主键,表类型(包,设置... ), ETC。
在我的测试中,我为所有类型的表做 10W 记录和 1W 记录,并且只选择/匹配非主键。
以下代码:
select_ets_test(Times) ->
MS = ets:fun2ms(fun(T) when T#ets_haoxian_template.count == 15 -> T end),
T1 = timer:tc(?MODULE, todo, [fun() -> ets:select(haoxian_test_bag, MS) end, Times]),
T2 = timer:tc(?MODULE, todo, [fun() -> ets:select(haoxian_test_set, MS) end, Times]),
T3 = timer:tc(?MODULE, todo, [fun() -> ets:select(haoxian_test_ordered_set, MS) end, Times]),
T4 = timer:tc(?MODULE, todo, [fun() -> ets:select(haoxian_test_duplicate_bag, MS) end, Times]),
io:format("select bag : ~p~n", [T1]),
io:format("select set : ~p~n", [T2]),
io:format("select ordered_set : ~p~n", [T3]),
io:format("select duplicate bag : ~p~n", [T4]).
match_ets_test(Times) ->
MS = #ets_haoxian_template{count = 15, _ = '_' },
T1 = timer:tc(?MODULE, todo, [fun() -> ets:match_object(haoxian_test_bag, MS) end, Times]),
T2 = timer:tc(?MODULE, todo, [fun() -> ets:match_object(haoxian_test_set, MS) end, Times]),
T3 = timer:tc(?MODULE, todo, [fun() -> ets:match_object(haoxian_test_ordered_set, MS) end, Times]),
T4 = timer:tc(?MODULE, todo, [fun() -> ets:match_object(haoxian_test_duplicate_bag, MS) end, Times]),
io:format("match bag : ~p~n", [T1]),
io:format("match set : ~p~n", [T2]),
io:format("match ordered_set : ~p~n", [T3]),
io:format("match duplicate bag : ~p~n", [T4]).
todo(_Fun, 0) ->
ok;
todo(Fun, Times) ->
Fun(),
todo(Fun, Times - 1).
记录如下:#ets_haoxian_template{type = X, count = Y, ...},keypose 是类型。
结果如下:1W测试:
insert bag : {324000,true}
insert set : {221000,true}
insert ordered_set : {108000,true}
insert duplicate bag : {173000,true}
select bag : {284000,ok}
select set : {255000,ok}
select ordered_set : {221000,ok}
select duplicate bag : {252000,ok}
match bag : {238000,ok}
match set : {192000,ok}
match ordered_set : {136000,ok}
match duplicate bag : {191000,ok}
10W测试:
insert bag : {1654000,true}
insert set : {1684000,true}
insert ordered_set : {981000,true}
insert duplicate bag : {1769000,true}
select bag : {3404000,ok}
select set : {3433000,ok}
select ordered_set : {2501000,ok}
select duplicate bag : {3678000,ok}
match bag : {2749000,ok}
match set : {2927000,ok}
match ordered_set : {1748000,ok}
match duplicate bag : {2923000,ok}
似乎匹配比选择更好?还是我的测试有问题???