快捷搜索: 王者荣耀 脱发

erlang数据库 ETS 工作原理分析

ETS 是erlang term strorage 的意思 文档见erl5.5.5/lib/stdlib-1.14.5/doc/html/index.html。 这个是beam里面很核心的一个功能。ets, dets, mnesia 组成了erlang的数据库,注意mnesia本身没有存储机制 它的存储就是ets 和dets。 用ets:i().看下可以知道 11 code set 254 11393 code_server 12 code_names set 48 5323 code_server 13 shell_records ordered_set 0 72 <0.25.0> ac_tab ac_tab set 6 853 application_controller file_io_servers file_io_servers set 0 279 file_server_2 global_locks global_locks set 0 279 global_name_server global_names global_names set 0 279 global_name_server global_names_ext global_names_ext set 0 279 global_name_server global_pid_ids global_pid_ids bag 0 279 global_name_server global_pid_names global_pid_names bag 0 279 global_name_server inet_cache inet_cache bag 0 279 inet_db inet_db inet_db set 21 528 inet_db inet_hosts inet_hosts set 1 310 inet_db 也就是说erlang的kernel 和stdlib库的实现都很依赖于这个ets. 文档里面一句话: This module is an interface to the Erlang built-in term storage BIFs. ets.erl本身只是一个封装的模块 用于检查参数等等 实际的工作都是bif作的,所以效率非常好。 看下otp_src_R11B-5ertsemulatoreamif.tab # # Bifs in ets module. # bif ets:all/0 bif erl.lang.ets:all/0 ebif_ets_all_0 bif ets:new/2 bif erl.lang.ets:new/2 ebif_ets_new_2 ... bif erl.lang.ets:match/1 ebif_ets_match_1 bif ets:match/2 bif erl.lang.ets:match/2 ebif_ets_match_2 bif ets:match/3 在emulator里面和ets实现有关的 有erl_db.c(界面) erl_db_hash.c(hash实现) erl_db_tree.c(tree实现) erl_db_util.c(match虚拟机等 ) 总代码有 将近有20,000行实现是很复杂的,据说下一版本会用jarray的算法来做效率更高。 ets的实现不是多线程安全的,数据不参加GC, 使用的时候要注意。 当我们要遍历ets的时候 可以用first/next来遍历 也可以用foldr foldl来看ets看成list来使用。但是这样使用的时候有效率问题 数据要从erts内部搬到process 当ets很大的时候就效率低。 这时候ets:select match MatchSpec来帮你了. ets内部实现了一个虚拟机把matchspec编译成opcode 然后eval的时候把需要的数据才拷贝到process去 大大减少了数据量. 这个方法类似于sqlite。 见db_match_set_compile 编译matchspec成opcode db_prog_match 运算opcode 细节可以看下代码。 这还不够 ets 考虑到matchspec比较难写 又提供了一个功能 fun2ms 可以把标准的erlang fun转换成matchspec.请参考ms_transform. 有了这些功能的辅助 ets使用起来就很方便了。
经验分享 程序员 微信小程序 职场和发展