[erlang-questions] BEAM micro-optimization: term comparison (> 0) versus pattern-matching

Mikael Pettersson <>
Sat Apr 15 20:13:22 CEST 2017


Suppose a frequently called function returns a positive integer (always a fixnum)
and a boolean "success" or "failure" indicator (even in the failure case the return
value is significant and will be used).  Which is better from a performance
perspective:

1. Tag the return value, {success, X} or {failure, Y}, and have callers pattern-match
   on that

or,

2. Indicate failure by negating Y, and have callers match on

      X when X > 0 -> success case;
      MinusY -> failure case % MinusY =< 0 is implicit

Option 2 avoids the consing overheads of option 1, but I'm worried that the X > 0
guard may be less optimized than a plain structural pattern-match.  The last time
I checked, term-comparisons would check inline for identity, and otherwise call
the general cmp() function which would then do a lot of type-casing.

In my pure Erlang code I'm using option 1, but I'm reimplementing the function
as a NIF, and would like to avoid the consing overheads is that's indeed better.


/Mikael


More information about the erlang-questions mailing list