[erlang-questions] cost of passing a gen_server state between functions

Hynek Vychodil <>
Sun Aug 8 19:45:56 CEST 2010

There should not be difference because if function do_something is
short (not in term of source code but result code) compiler will often
inline it and then do same optimization as if work done in function.
Even compiler don't inline it should not be big difference because
state will be pass by pointer to it and call overhead should be low
compared to function itself. Biggest difference will be when you do
external call (m:f() call form or worse M:f() ot M:F()) when overhead
is bigger and compiler can't inline and can't do any optimization
because it would violate hot code swap promise. Note that state is
never copied in function call in Erlang. Erlang do copy on write when
state is modified but not in function calls even for external calls.

If you are curious you can do a lot of things. For example
1/ compile using 'S' option and look at result
2/ write some sort of benchmark and ask if you will see something unexpected

On Sun, Aug 8, 2010 at 3:21 AM, Pablo Platt <> wrote:
> Hi,
> Is there a difference in manipulating the state of a gen_server inside a single
> function
> and passing the state to another function that manipulate it?
> Is there a difference if the othe function is in another module?
> %The state is been manipulated in the handl_cast function:
> handle_cast({something, I}, State1) ->
>    OldList = State1#state.l,
>    NewList = [I | OldList],
>    State2 = State#state1{l=NewList},
>    {noreply, State2}.
> %handle_cast pass the state to another function that changes it:
> handle_cast({something, I}, State) ->
>    State2 = do_something(I, State),
>    {noreply, State2}.
> do_something(I, State) ->
>    State2 = State#state1{l=NewList},
>    State2.
> Thanks

--Hynek (Pichi) Vychodil

Analyze your data in minutes. Share your insights instantly. Thrill
your boss.  Be a data hero!
Try GoodData now for free: www.gooddata.com

More information about the erlang-questions mailing list