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

Pablo Platt pablo.platt@REDACTED
Mon Aug 9 22:37:19 CEST 2010


Shorter functions is always more readable so I like your version better.

Thank you for the clarifications and coding style suggestions.




________________________________
From: Robert Virding <rvirding@REDACTED>
To: Pablo Platt <pablo.platt@REDACTED>
Cc: erlang-questions@REDACTED
Sent: Mon, August 9, 2010 9:21:47 PM
Subject: Re: [erlang-questions] cost of passing a gen_server state between 
functions

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