erlang对binary的优化

阅读更多

 

erlang binary:

  container

    1 refc(reference-counted) binaries

      1 ProcBin: link list, to garbage collect

      2 binary object: outside all process heaps

    2 heap binaries: up to 64B, process heap, copied when sent

  reference

    1 sub binaries: a reference to a part of refc or heap binary

    2 match contexts

 

 

-module(test_binary).

-export([test/0]).

test() ->
    test1(),
    test2(),
    test3(),
    ok.


%% 超过64是refc binary
test1() ->
    A = binary:copy(<<1>>,65),
    <<_:10/binary,B:10/binary,_/binary>> = A,
    Pid = spawn(
            fun() ->
                    receive
                        Bin ->
                            65 = binary:referenced_byte_size(Bin)
                    end
            end),
    Pid ! B.

%% 不超过64是heap binary
test2() ->
    A = binary:copy(<<1>>,64),
    <<_:10/binary,B:10/binary,_/binary>> = A,
    Pid = spawn(
            fun() ->
                    receive
                        Bin ->
                            10 = binary:referenced_byte_size(Bin)
                    end
            end),
    Pid ! B.
    
%% append创建新的refc binary
test3() ->
    A = binary:copy(<<1>>,60),
    <<_:10/binary,B:10/binary,_/binary>> = <>,
    Pid = spawn(
            fun() ->
                    receive
                        Bin ->
                            61 = binary:referenced_byte_size(Bin)
                    end
            end),
    Pid ! B.

%% refc binary如果需要被改动,则尽量在原有的refc binary上改;
%% 如果被共享,则需要拷贝
%% efficiency_guide/binaryhandling.html#id65923

你可能感兴趣的:(erlang对binary的优化)