[erlang-questions] Random newbie stuff

Thomas Lindgren thomasl_erlang@REDACTED
Sun Nov 4 16:36:01 CET 2007


--- Dennis Byrne <dbyrne@REDACTED> wrote:

> Hello Ulf,
> 
> If you have a function that is 100% predictable,
> couldn't there be some 
> serious performance gains given that the function is
> frequently passed the 
> same message?  In other words, why put a core to
> work calculating the 
> result you gave last time someone sent you a given
> message?  It would be 
> better to use this function to spawn a process that
> could use the process 
> dictionary as a cache (one that would never expire).
> 
> 
> Unless ... are gets and puts to the dictionary
> thread safe?

Since put/get is local to the thread, they are.
Anyway, here is global memoization:

- start a set table ?memo (not shown)
- if M:F(A1,...,An) has been called before, use the
precomputed result
- otherwise, compute it, store the result and return
it

-module(memo).
...

memo_apply(M, F, As) ->
    Key = {M, F, As},
    case ets:lookup(?memo, Key) of
	[{_, Res}] ->
	    Res;
	[] ->
	    case catch apply(M, F, As) of
		{'EXIT', Rsn} ->
		    exit(Rsn);
		Res ->
		    ets:insert(?memo, {Key, Res}),
		    Res
	    end
    end.

Do note that in general memoization can leak a lot of
memory, and that for Erlang you will have to clear the
table when there is code change.

Best,
Thomas


__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 



More information about the erlang-questions mailing list