Search code examples
erlanggen-server

Erlang: gen_server or my own custom server?


I need to write a server that will receive instructions from other modules and take actions depending on the instructions received. Efficiency is my main concern. So do I use gen_server or do I write my own server. By "my own server" I mean something like:

-module(myserver).
-export([start/0, loop/0]).

start() ->
        spawn(myserver, loop, []).

loop() ->
   receive
        {From, Msg} -> %Do some action here... ;
        message2 -> %Do some action here...;
        message3 -> %Do some action here...;
        message4 -> %Do some action here...;
        .
        .
        .
        _-> ok
   end,
   loop().

So to use myserver, I will probably register the process under a registered name while starting it, and then each client will send messages to the server using this pid.

So should I use this method, or instead implement the server using the gen_server behaviour? Are there any advantages to using gen_server? But will using gen_server add any overhead, when compared to myserver?


Solution

  • gen_server will have a negligible overhead compared to self-implemented servers, because it requires a few additional function calls per message (one of which is dynamic). I don't think you should consider this at this point of implementation. Did you changed your mind at any point, moving from gen_server to your own server should be straightforward.

    What you get with gen_server compared to a simple loop is:

    • debugging (with sys)
    • SASL logging
    • hibernation support
    • code upgrade support