static variables?

Richard Carlsson <>
Tue Aug 22 16:16:02 CEST 2006

Yariv Sadan wrote:
> Strangely, I find myself at a crossroads where I would like to have
> static (i.e. per-module) variables. Yes -- I know -- this would be a
> gross violation of the shared-nothing principle -- but then I would be
> just as happy if all static variables were "final" so there's no way
> that two processes would trample on the same data.

So, what you really are saying is that you want per-module
constants? That is certainly no violation of anything, and can
easily be expressed as nullary functions, as in your example.

> Here's basically what I want to have:
> -module(person).
> -compile(export_all).
> fields = ["name", "age"].
> get_fields() ->
>  fields.

I interpret your question as "is there a way of defining a
constant complex value such as a list, without wasting time
on rebuilding the structure each time it is accessed?".

Well, ideally, the compiler should construct this constant and
place it in memory once and for all, so that each access to
the fields() function just returns a pointer to that memory.
Sadly, the Beam compiler is not doing this yet, because of
memory management implementation issues. If you HiPE-compile
your program, however, you will get this effect. (And even
the Beam compiler does some optimizations when it comes to
constructing constant strings.)

My advice would be: don't worry too much about the efficiency,
but for starters consider using a list of atoms instead of a
list of strings. It is easy to convert atoms to strings when 
necessary, and comparing atoms for equivalence is much cheaper.
For example:

fields() ->
  [name, age].

This has quite low cost. If you need much larger constant
structures (hundreds of bytes) that are accessed often, then
start considering passing them around in a separate variable,
or in a field of a state record that you pass around.


More information about the erlang-questions mailing list