erlang中application来获取变量与ets获取变量的速度比较

今天有些数据要缓存起来获取,分别比较了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已经封装好逻辑了,使用相对简单。

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.

代码实现:

%% 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就不贴代码了,我现在还不够深入理解,以后有机会再理解。

转载于:https://my.oschina.net/u/191928/blog/684893

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值