lists ,maps 和record是erlang最为常用的数据结构,lists使用方便简单,maps则查询高效,record则需要预定义,可扩展性差,各有各的优。本文做一下lists和maps的性能对比(再对比一下dict),代码如下(record操作不便则不做比较)。
%%通过注释部分代码做以下测试
%%timer:tc(lib_test, test_struct, [10000,#{}]).
%%timer:tc(lib_test, test_struct, [10000,[]]).
test_struct(0,R) ->
Fun = fun({K,V}) -> K+1,V+1 end, lists:foreach(Fun,R), %%遍历测试
Fun = fun(K,V) -> K+1,V+1 end, maps:map(Fun,R),
ok;
test_struct(Num, R) ->
NewR = [{Num, Num}|R], lists:keyfind(5000,1,NewR), %%插入查询测试
NewR = R#{Num=>Num}, maps:get(5000, NewR, 0),
test_struct(Num-1, NewR).
做10000次的插入查询测试结果:
lists 50736微秒
maps 4670微秒
dict 60236微秒
做10000次的遍历结果:
lists 523微秒
maps 8337微秒
dict 4426微秒
对比总结:
对比测试数据