Erlang / Erlang Advanced Interview questions
How can you optimize binary pattern matching for parsing variable-length network protocols?
Erlang's bit-syntax lets you decode a protocol header directly in a pattern, including fields whose length depends on an earlier field — a common shape in real network protocols (a length-prefixed payload, for instance).
parse(<<Type:8, Len:16, Payload:Len/binary, Rest/binary>>) -> {Type, Payload, Rest}.
A few concrete performance habits matter at scale:
- Match the sub-binary, don't copy it — the
Payload:Len/binarypattern above creates a reference into the original binary rather than copying bytes, as long as the binary is large enough to be reference-counted. - Avoid rebuilding accumulated binaries with
<<Acc/binary, New/binary>>in a tight loop — each concatenation can copy the growing accumulator; prefer collecting parts in a list and callinglist_to_binary/1once at the end. - Use
Rest/binarygenerously to keep unconsumed trailing bytes as a reference rather than slicing them into a new copy prematurely.
More Related questions...