Pattern matching vs. ETS lookups

Vance Shipley <>
Mon Feb 16 23:07:57 CET 2004


Serge,

You don't necessarily need ETS either.  I always resist using
ETS when the data is not needed globally.  If it's only needed
by one process it should properly be kept within that 'cause
it's nobody else's business.


Put the mapping into a terms file:

     {0, {SomeAPIModule, SomeAPIFunction}}.
     {1, {SomeAPIModule, SomeOtherAPIFunction}.
     ...
     {3000, {SomeOtherAPIModule, YetAnotherAPIFunction}.


In your startup function create a local state with the
mappings.  In your handler lookup up the module and function
from the state data.  Here are a couple ways to do it 
using a gen_server:

Simple list:

     init(Path) ->
          file:consult(Path).  %% conviently returns {ok, State}
     
     handle_info(<<FunctionID:16, Body/binary>>, State) ->
          {M, F} = lists:keysearch(FunctionID, 2, State),
          M:F(Body).
     
     
General balanced trees:
     
     init(Path) ->
          {ok, List} = file:consult(Path),
          {ok, gb_trees:from_ordict(List)}.
     
     handle_info(<<FunctionID:16, Body/binary>>, State) ->
          {M, F} = gb_trees:get(FunctionID, State},
          M:F(Body).
     

I can't say which method is more effecient, hardcoded function
clauses, or a lookup function however the above strikes me as
more appropriate than ETS.


	-Vance



More information about the erlang-questions mailing list