特别注意的是sub binary的使用。举个例子,从一个大的Binary中取出以某个字节结束的一句:
extract_str_end_with_tag(Data, Tag) -> extract_str_end_with_tag2(Data, <<>>, Tag). extract_str_end_with_tag2(<>, Buffer, Tag) -> extract_str_end_with_tag3(Buffer, T); %% 留意这里 extract_str_end_with_tag2(<>, Buffer, Tag) -> extract_str_end_with_tag2(T, < >, Tag); extract_str_end_with_tag2(<<>>, Buffer, Tag) -> {not_found, Buffer}. extract_str_end_with_tag3(Str, NextStr) -> {found, Str, size(Str), NextStr}.
上面的代码由于将sub binary T 传递给 extract_str_end_with_tag3/2,在使用 erlc +bin_opt_info 编译的时候会提示:
引用
Warning: NOT OPTIMIZED: called function extract_str_end_with_tag3/
2 does not begin with a suitable binary matching instruction
2 does not begin with a suitable binary matching instruction
我的做法是加入一个是否匹配的字段:
extract_str_end_with_tag(Data, Tag) -> extract_str_end_with_tag2(Data, <<>>, Tag, not_found). extract_str_end_with_tag2(RestBinary, Buffer, _, found) -> extract_str_end_with_tag3(Buffer, RestBinary); %在found的时候再将RestBinary进行传递 extract_str_end_with_tag2(<>, Buffer, Tag, _) -> extract_str_end_with_tag2(T, Buffer, Tag, found); %这里不使用T extract_str_end_with_tag2(<>, Buffer, Tag, not_found) -> extract_str_end_with_tag2(T, < >, Tag, not_found); extract_str_end_with_tag2(<<>>, Buffer, _, _) -> {not_found, Buffer}. extract_str_end_with_tag3(Str, NextStr) -> {found, Str, size(Str), NextStr}.
这样在编译时就可以进行优化
引用
Warning: OPTIMIZED: creation of sub binary delayed