我找 “函数 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
我读过一些关于比较选择和匹配的文章,我得出结论,有一些影响结果的因素,例如表中的记录数量,是否选择/匹配主键,表种类(袋,集... ), 等等。
在我的测试中,我对所有类型的表进行了 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}
似乎匹配比选择更好?还是我的测试有问题???
最佳答案
match
函数使用特殊的元组语法 ( match_pattern
) 来决定返回什么。select
函数采用特殊的元组语法( match_spec
),它是 match_pattern
的超集,能够指定守卫并从结果集中提取元素(而不仅仅是返回匹配的键)。
我的理解是:
select
编译match_spec
进入匿名函数,加快运行速度 match_pattern
更快地消除误报。 (因为他们会先运行)在琐碎的非特定用例中,
select
只是在 match
周围做了很多工作.在非平凡的更常见用例中,select
会更快地给你你真正想要的东西。
关于performance - Erlang:ets 选择和匹配性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29505161/