The following sample code is from Joe Armstrong’s Programming Erlang book:
max(N) ->
Max = erlang:system_info(process_list),
io:format("Maximum allowed processes:~p~n",[Max]),
statistics(runtime),
statistics(wall_clock),
L = for(1, N, fun() -> spawn(fun() -> wait() end) end),
{_, Time1} = statistics(runtime),
{_, Time2} = statistics(wall_clock),
lists:foreach(fun(Pid) -> Pid ! die end, L),
U1 = Time1 * 1000 / N,
U2 = Time2 * 1000 / N,
io:format("Process spawn time=~p (~p) microseconds~n",
[U1, U2]).
My question is dealing with Erlang fundamentals. It looks like Joe used for() to spawn processes, followed by a lists:foreach to die them. Is there a reason to use one over the other? Why not use for() again to iterate over the the spawned process list and send them a die message? Is there an efficiency optimization here that I’m missing?
lists:foreachsaves you the trouble of determining the length of the list ahead of time, and of specifying it as an argument. Theforinvocation needs to know how long to make the list, so it’s necessary.for()is usually used as a last resort when there’s nothing more appropriate.