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

Robert Virding rvirding@REDACTED
Mon Aug 9 20:21:47 CEST 2010


On 9 August 2010 03:10, Pablo Platt <pablo.platt@REDACTED> wrote:
> Thank you Hynek and Robert.
>
> The reason I asked this question is because I have one gen_server that
> handles several sessions for the same user.
> I have several session types for different types of connections: socket,
> http...
> When the gen_server receive a message it passes it to an handler along with
> the gen_server's state.
> Each session type defines a different handler (module).
> The handler process the message and reply with a new state.
>
> Most of the operations on the state are setting a new value in a record,
> reading values and adding new items to lists.
> So from your explanation I understand that there is no copy. The state is
> passed by reference
> and that as long as I append new values to the head of lists in the state
> I'm safe.

The new state is also returned by reference. One thing you may
consider is that if the state contains groups of values for each
session type then create separate records for them:

-record(state, {socket,other_type,...}).
-record(socket_state, {...}).
-record(other_type_state, {...}).
...

You can then in the can in the top dispatcher just extra/reinsert just
that part of the state. It will make it easier to keep each session
type module independent. This will, of course, not work if there are
state values which are shared between the different session types.

> % inside the socket session module:
> handle_message(State, Message) ->
>     do_something_with_message(Message),
>     Log = State#state.log,
>     NewLog = [Message | Log],
>     NewState = State#state{log=NewLog},
>     NewState.

You don't really need to save all the intermediate values in
variables, it could just as well have been written:

handle_message(State, Message) ->
    do_something_with_message(Message),
    NewLog = [Message | State#state.log],
    State#state{log=NewLog}.
.
The resulting code will more or less be the same so here again it is a
matter of taste and which feels best.

Robert


More information about the erlang-questions mailing list