论坛首页 综合技术论坛

binary的常量优化

浏览 1852 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-10-06  
erlang的binary在这个网络程序里面占着非常重要的地位,所以otp团队采用了非常多的优化手段包括:

1.  binary操作对应着 opcode
2. 根据生命期和作用,有4种类型的binary
3. hipe优化,把bs_操作直接翻译成asm指令
4. 编译器层面消除无必须的操作。


下面的例子就是演示4的特性:

yu-fengdemacbook-2:~ yufeng$ cat bin.erl
-module(bin).
-export([start/1]).

start(A)->
    B1= <<12>>,
    B2 = <<B1/binary, 5.0/float>>,
    B3= <<B2/binary,  "yes">>,
% B3的值是预先可以知道的, 无需一步步的构造

    <<"abcd", 3:32,B3:128/binary,_/binary>> = <<"abcd1234",A/binary,2:32, 8773:64, "a", 5.0/float>>.

% 2:32, 8773:64, "a", 5.0/float 这些都是预先知道的 直接翻译成二进制流。

yu-fengdemacbook-2:~ yufeng$ erlc +"'S'" bin.erl
yu-fengdemacbook-2:~ yufeng$ cat bin.S
{module, bin}.  %% version = 0

{exports, [{module_info,0},{module_info,1},{start,1}]}.

{attributes, []}.

{labels, 8}.


{function, start, 1, 2}.
  {label,1}.
    {func_info,{atom,bin},{atom,start},1}.
  {label,2}.
    {move,{integer,0},{x,1}}.
    {gc_bif,byte_size,{f,0},2,[{x,0}],{x,2}}.
    {bs_add,{f,0},[{x,1},{x,2},1],{x,1}}.
    {bs_add,{f,0},[{x,1},{integer,29},1],{x,1}}.
    {bs_init2,{f,0},{x,1},0,1,{field_flags,[]},{x,1}}.
    {bs_put_string,8,{string,"abcd1234"}}.
    {bs_put_binary,{f,0},{atom,all},8,{field_flags,[unsigned,big]},{x,0}}.

%% 一步到位
    {bs_put_string,21,
                   {string,[0,0,0,2,0,0,0,0,0,0,34,69,97,64,20,0,0,0,0,0,0]}}.

    {test,bs_start_match2,{f,3},[{x,1},2,0,{x,0}]}.
    {test,bs_match_string,{f,3},[{x,0},64,{string,[97,98,99,100,0,0,0,3]}]}.
%%  一步到位

    {test,bs_get_binary2,
          {f,3},
          [{x,0},
           2,
           {integer,128},
           8,
           {field_flags,[{anno,[8,{file,"./bin.erl"}]},unsigned,big]},
           {x,2}]}.
    {test,bs_skip_bits2,
          {f,3},
          [{x,0},
           {atom,all},
           8,
           {field_flags,[{anno,[8,{file,"./bin.erl"}]},unsigned,big]}]}.
    {test,is_eq_exact,
          {f,3},
          [{x,2},{literal,<<12,64,20,0,0,0,0,0,0,121,101,115>>}]}.
%%  一步到位

    {move,{x,1},{x,0}}.
    return.
  {label,3}.
    {badmatch,{x,1}}.


{function, module_info, 0, 5}.
  {label,4}.
    {func_info,{atom,bin},{atom,module_info},0}.
  {label,5}.
    {move,{atom,bin},{x,0}}.
    {call_ext_only,1,{extfunc,erlang,get_module_info,1}}.


{function, module_info, 1, 7}.
  {label,6}.
    {func_info,{atom,bin},{atom,module_info},1}.
  {label,7}.
    {move,{x,0},{x,1}}.
    {move,{atom,bin},{x,0}}.
    {call_ext_only,2,{extfunc,erlang,get_module_info,2}}.

所以我们在使用binary的时候, 尽可能的利用这个特性。

论坛首页 综合技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics