[erlang-questions] newbie: equality

Richard Carlsson <>
Fri Dec 28 17:35:06 CET 2007


Jonathan Amsterdam wrote:
> Two comments on equality in Erlang.
> 
> 1. The Reference Manual says that the only difference between == and
> =:= is that the former will coerce ints to floats. (By the way, the
> sentence that expresses this says "All comparison operators except =:=
> and =/= are of type coerce". That isn't grammatical English, unless
> "of type coerce" is some term of art that I don't know.) Why then does
> Joe Armstrong in his book strongly advise using =:= in most cases? Is
> it just the slight performance hit or is there a deeper reason?

Various reasons:
  a) it is slightly cheaper

  b) =:= is the same (exact) equality test that the pattern matching
     does, so you avoid nasty surprises with floats matching integers

  c) =:= gives better hints to the compiler, Dialyzer, and any
     other program analysis tools, since there is no coercion

  d) it has the words Don't Panic inscribed in large friendly letters
     on its cover

> 2. It seems (from my experimentation) that =:= performs an initial
> pointer-equality check. This is good and expected, but I think it
> should be documented in the reference manual (i.e. made part of the
> language semantics). Although it is in one sense just an efficiency
> hack, it can have a dramatic effect on how one codes. E.g. I need a
> list of key-value pairs suitable for use with lists:keysearch and
> friends. May I use large objects for the keys, or must I use small
> unique IDs instead?

The pointer equality optimization will only be effective as long as
you have complete control over the data. For example, an object that
has been on a round trip to another process is likely to have been
copied (depending on the runtime system flavour), so the pointers
will be different, causing a costly comparison of the whole objects.
I suggest you use small keys right from the start, to get that warm
fuzzy future-safe feeling. (Or as a compromise, you might just use a
dict with large keys, since it uses hashing. You shouldn't really be
using lists:keysearch anyway, if efficiency is an issue, unless you
know you will always have lists of only a few elements.)

    /Richard

-- 
 "Having users is like optimization: the wise course is to delay it."
   -- Paul Graham



More information about the erlang-questions mailing list