erlang中application来获取变量与ets获取变量的速度比较
2016-05-31 00:00
330 查看
今天有些数据要缓存起来获取,分别比较了application和ets获取变量的方法。
结论:
appcation:get_env/2 方法和 ets:lookup/2 方法都是只需要一次ets读,最快。如果在程序运行过程中插入数据可以选择ets:lookup/2,像现在rebar3可以在程序启动后把数据存储在appcation变量里面,可以选择appcation:get_env/2。另外ets:lookup/2要自己写比较逻辑,appcation:get_env/2已经封装好逻辑了,使用相对简单。
参考:[erlang-questions] "speed question"
代码实现:
可以看到application:get_env/1要使用ets:match/2方法,理论上要慢很多。
代码实现都是从名为ac_tab的ets表里面读取变量内容。
mnesia就不贴代码了,我现在还不够深入理解,以后有机会再理解。
结论:
appcation:get_env/2 方法和 ets:lookup/2 方法都是只需要一次ets读,最快。如果在程序运行过程中插入数据可以选择ets:lookup/2,像现在rebar3可以在程序启动后把数据存储在appcation变量里面,可以选择appcation:get_env/2。另外ets:lookup/2要自己写比较逻辑,appcation:get_env/2已经封装好逻辑了,使用相对简单。
application:get_env/1方法需要2次读ets,相对较慢。
mnesia:dirty_read/1方法需要3次读ets,最慢,但可以在多个节点中使用。
参考:[erlang-questions] "speed question"
Generally, the performance should be insignificant, but… ets:lookup/2: 1 ets read (duh), but obviously, you need to write more code application:get_env/2: 1 ets read application:get_env/1: 2 ets reads (one to find the current application) mnesia:dirty_read/1: - 1 get() - 3 ets reads, if data is local (where_to_read, storage_type, lookup) Beyond the performance differences, there are semantic issues. Application environment variables are really meant to be static, either hard-coded in the .app file, or overridden at startup. They can also be changed at upgrades, but the expectation isn't that they change dynamically. In fact, for data that is truly static, the fastest access is if the data is simply hard-coded in an erlang module. Given that modules are easy to reload, these values can still be changed with low frequency. So for system preferences, it is generally better to store the values in a database.
代码实现:
[code=language-xml]%% appcation.erl get_env(Key) -> application_controller:get_pid_env(group_leader(), Key). get_env(Application, Key) -> application_controller:get_env(Application, Key). %% application_controller.erl get_pid_env(Master, Key) -> case ets:match(ac_tab, {{application_master, '$1'}, Master}) of [[AppName]] -> get_env(AppName, Key); _ -> undefined end. get_env(AppName, Key) -> case ets:lookup(ac_tab, {env, AppName, Key}) of [{_, Val}] -> {ok, Val}; _ -> undefined end.
可以看到application:get_env/1要使用ets:match/2方法,理论上要慢很多。
代码实现都是从名为ac_tab的ets表里面读取变量内容。
mnesia就不贴代码了,我现在还不够深入理解,以后有机会再理解。
相关文章推荐
- android 获取AndroidManifest文件中meta-data的值
- android6.0 权限管理 方案
- iOS设置夜间模式
- iOS中格式化输出日志
- iOS 一步一步带你实现引导页
- media server分析
- 下拉列表刷新,分页加载
- android 使用Scroller实现缓慢移动
- Android Jni之Helloworld
- Android 快传 文件互传
- Android线程池
- Android开源中国客户端学习 (自定义View)左右滑动控件ScrollLayout
- Android系统的上下文对象Context
- android studio 使用备忘
- iOS开发自动补全第18位身份证号码的X
- iOS开发总结之 Foundation框架总结
- Android官方说明-Activity任务栈
- iOS-静态库(1)
- 在sha1 keytool不是内部或外部命令 android studio
- Android Studio详细使用教程