Iteration over lists

Emil Öberg (LN/EAB) <>
Thu Mar 16 17:52:01 CET 2006


 Hi.

Sitting here doing some profiling on our system and started to wonder about the performance of recursion/map/list comprehensions. Made a small test program just to compare them and got some (to me at least) surprising results. Lists:map() is nearly twice as slow as recursion, even when list is reversed, and list comprehension is even slower! Could anyone explain this? It is kind of disturbing to be forced to use messy recursion just because your code is time-critical.


List				rev				mapping	list
elements	recursion	recursion	mapping	w. Fun	comprh.	
5		0.0690	0.0770	0.0940	0.0830	0.0820	
10		0.1200	0.1320	0.1600	0.1530	0.1490	
50		0.5240	0.5450	0.7540	0.8900	0.7660	
100		1.1110	1.0490	1.4800	1.4880	1.5800	
200		2.5330	2.1180	4.2030	5.7090	2.9500	
500		5.5410	6.6350	9.5430	9.0360	9.4000	
700		9.0160	7.2820	12.7840	12.1180	13.9340	
1000		12.2220	12.4670	15.7670	20.7170	18.0760	
2000		25.1110	26.1110	31.2840	36.3090	44.8230	
3000		40.2820	42.2100	66.4730	66.8280	89.7050	
4000		59.8470	56.5540	102.6200	102.7070	133.7110	
5000		81.1000	85.1060	139.0810	138.8840	179.1730	
6000		98.4590	103.7620	176.6980	175.7730	222.7360



What I measured was (list genereated by lists:seq(1,N)):

recursion([H | T], Acc) ->
    recursion(T, [integer_to_list(H) | Acc]);
recursion([], Acc) -> 
    Acc.

revrecursion([H | T], Acc) ->
    revrecursion(T, [integer_to_list(H) | Acc]);
revrecursion([], Acc) -> 
    lists:reverse(Acc).

mapfun(L) ->
    lists:map(fun erlang:integer_to_list/1, L).

mapping(L) ->
    lists:map({erlang, integer_to_list}, L).

listcompr(L) ->
    [erlang:integer_to_list(X) || X <- L].


	/Emil



More information about the erlang-questions mailing list