yuanti.primat.es

yuanti.primat.es

programming archaeology, pedantics, and machine intelligence

29 Nov 2012

The Ref Trick

A common Erlang performance issue is that selective receives can take a lot of time when the receiving process has a long message-queue. R14 introduced a compile-time optimization which allows for O(1) receive. If static analysis can show that a receive-statement selects exclusively based on a freshly generated reference, special BEAM instructions will be generated which avoid a scan of the message-queue.

In particular, if instead of

receive bar -> ok end

we write

Ref = make_ref(),
...
receive {Ref, bar} -> ok end

we’ll benefit from this optimization.

Looking at the BEAM assembly (erlc -S), we see that the compiler inserted recv_mark and recv_set instructions to save the current message-queue pointer and jump to it just before the receive.