[erlang-questions] serializing functions

Richard Carlsson richardc@REDACTED
Sun Nov 16 22:59:06 CET 2008


damien morton wrote:
> If I take the most basic of functions, e.g. fun()->0 end. and serialize
> it using term_to_binary(), it seems that this function is serialized to
> 650 bytes.

If you write "fun ... end" in the shell, you will get a rather
peculiar closure that actually contains the abstract syntax tree
for the fun-expression (which will be interpreted by erl_eval
when the closure is applied). That's why it's rather big.

> I guess I was wondering if its better to send a Mod:Fun pair from one
> node to another, or to send an actual function() object. Now, I am still
> not sure if a function() can be sent over the wire, but a Mod:Fun pair
> sure is a whole lot more compact.
> 
> What are the normal best practices when handling functions that might be
> send over the wire? Prefer Mod:Fun over function()?

To have a module send one of its anonymous funs to another node will
work (and won't be larger than the size of any captured variables
plus a few additional words to identify the fun), but it requires
that the code (for the module in which the fun is written) on both
nodes is exactly the same.

You can have the best of two worlds by sending e.g. "fun foo:bar/0",
which has a compact encoding and always calls the latest version of
module foo, but is still a fun-object that you can apply as F().

    /Richard

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



More information about the erlang-questions mailing list