﻿ 【原译】Erlang列表处理（Efficiency Guide） - 鸿网互联

# 【原译】Erlang列表处理（Efficiency Guide）

=====================================================================================================

List handling 1  Creating a list 创建一个列表

Lists can only be built starting from the end and attaching list elements at the beginning. If you use the ++ operator like this

List1 ++ List2

you will create a new list which is copy of the elements in List1, followed by List2. Looking at how lists:append/1 or ++would be implemented in plain Erlang, it can be seen clearly that the first list is copied:

append([H|T], Tail) -> [H|append(T, Tail)]; append([], Tail) -> Tail.

So the important thing when recursing and building a list is to make sure that you attach the new elements to the beginning of the list, so that you build a list, and not hundreds or thousands of copies of the growing result list.

Let us first look at how it should not be done:

DO NOT

Here we are not a building a list; in each iteration step we create a new list that is one element longer than the new previous list.

To avoid copying the result in each iteration, we must build the list in reverse order and reverse the list when we are done:

DO

tail_recursive_fib(N) -> tail_recursive_fib(N, 0, 1, []). tail_recursive_fib(0, _Current, _Next, Fibs) -> lists:reverse(Fibs); tail_recursive_fib(N, Current, Next, Fibs) -> tail_recursive_fib(N - 1, Next, Current + Next, [Current|Fibs]).

2  List comprehensions 列表解析

Lists comprehensions still have a reputation for being slow. They used to be implemented using funs, which used to be slow.

In recent Erlang/OTP releases (including R12B), a list comprehension

[Expr(E) || E <- List]

is basically translated to a local function

'lc^0'([E|Tail], Expr) -> [Expr(E)|'lc^0'(Tail, Expr)]; 'lc^0'([], _Expr) -> [].

In R12B, if the result of the list comprehension will obviously not be used, a list will not be constructed. For instance, in this code

[io:put_chars(E) || E <- List], ok.

or in this code

. . . case Var of ... -> [io:put_chars(E) || E <- List]; ... -> end, some_function(...), . . .

the value is neither assigned to a variable, nor passed to another function, nor returned, so there is no need to construct a list and the compiler will simplify the code for the list comprehension to

'lc^0'([E|Tail], Expr) -> Expr(E), 'lc^0'(Tail, Expr); 'lc^0'([], _Expr) -> [].

3  Deep and flat lists 深度扁平列表

<