下面是添加二进制字节的简单实现。根据 eprof 的说法,它很慢(大约需要 10% 的总时间 - 主要是因为很多调用binary:part/3
)。
如何优化?
calc_checksum(Packet) when is_binary(Packet)->
calc_checksum(Packet, 0).
calc_checksum(<<>>, Acc) ->
Acc band 16#FFFF;
calc_checksum(Packet, Acc) when is_binary(Packet) ->
W = binary:decode_unsigned(binary:part(Packet, 0, 2), little),
NextAcc = Acc + W,
NextBytes = binary:part(Packet, byte_size(Packet), -(byte_size(Packet)-2)),
calc_checksum(NextBytes, NextAcc).