1 year ago
#287391
Sidharth Gupta
erlang lists:foreach/lists:foldl/lists:foldr consumes more memory than using tail recursion
I ran a query using nested lists:foreach on the list of size 15000, each having lists of size about 37. This query consumed more than 5 Gb of memory, but when query was ran using tail recursion memory usage was under 1 Gb. Can anyone explain how and why is there so much difference as internally lists:foreach is also implemented using tail recursion.
ForEach =fun
Foreach(F, [Hd|Tail]) ->
F(Hd),
Foreach(F, Tail);
Foreach(F, []) when is_function(F, 1) -> ok
end.
RackFunc = fun(RackId) ->
[RackRef] = mnesia:dirty_read(rackref, RackId),
SlotDetails = RackRef#rackref.slot_details,
ForEach(SlotFunc, SlotDetails)
end.
SlotFunc = fun({SlotId, SlotProperties}) ->
feature
end.
ForEach(RackFunc,RACKIDLIST)
%%Function using library:
G = fun(RackIds)->
lists:foreach(
fun(RackId) ->
[RackRef] = mnesia:dirty_read(rackref, RackId),
SlotDetails = RackRef#rackref.slot_details,
lists:foreach(
fun({SlotId, SlotProperties}) ->
feature
end
end, SlotDetails)
end, RackIds)
end.
erlang
erlang-shell
erlang-stdlib
0 Answers
Your Answer