In many cases, particularly where the data is destined for the network you can avoid the concatenation by constructing an io_list instead.
B3 = [B1, B2],
gen_tcp:send(Socket, B3).
This is O(1) as it avoids copying either binary. gen_tcp:send will accept the deep list and walk the structure for output. (A two element list takes very little additional memory, so the memory overhead is small.) In some cases (repeated appends to the same binary), Erlang now has optimisations that avoid copying the binary being appended to so using io_lists may be less relevant: http://erlang.org/doc/efficiency_guide/binaryhandling.html#constructing-binaries Historical note: I originally advised only the io_list solution and a lot of commenters correctly point out that I failed to answer the question. Hopefully, the accepted answer is now complete. (11 years later!)
5条答案
按热度按时间nwsw7zdq1#
kxe2p93d2#
You can concatenate binaries using bit syntax:
In many cases, particularly where the data is destined for the network you can avoid the concatenation by constructing an io_list instead.
This is O(1) as it avoids copying either binary.
gen_tcp:send
will accept the deep list and walk the structure for output. (A two element list takes very little additional memory, so the memory overhead is small.)In some cases (repeated appends to the same binary), Erlang now has optimisations that avoid copying the binary being appended to so using io_lists may be less relevant: http://erlang.org/doc/efficiency_guide/binaryhandling.html#constructing-binaries
Historical note: I originally advised only the io_list solution and a lot of commenters correctly point out that I failed to answer the question. Hopefully, the accepted answer is now complete. (11 years later!)
bn31dyow3#
要使用io_list,可以执行以下操作:
这是很好的和清晰的。你也可以使用清单和东西在那里,如果它更方便。
lnxxn5zx4#
在最后一个答案的基础上:
eni9jsuy5#
使用erlang函数list_to_binary(List),您可以在此处找到文档:http://www.erlang.org/documentation/doc-5.4.13/lib/kernel-2.10.13/doc/html/erlang.html#list_to_binary/1