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_clo开发者_如何学JAVAck),
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:foreach
saves you the trouble of determining the length of the list ahead of time, and of specifying it as an argument. The for
invocation 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.
For the record, another way to express for
and foreach
is as list comprehensions:
for:
[spawn(fun() -> wait() end) || _ <- lists:seq(1, N)]
foreach:
[Pid ! die || Pid <- L]
精彩评论