本文共 2070 字,大约阅读时间需要 6 分钟。
In the following situations, you can easily avoid calling lists:flatten/1:
Port example
DO
... port_command(Port, DeepList) ...
DO NOT
... port_command(Port, lists:flatten(DeepList)) ...
A common way to send a zero-terminated string to a port is the following:
DO NOT
... TerminatedStr = String ++ [0], % String="foo" => [$f, $o, $o, 0] port_command(Port, TerminatedStr) ...
Instead do like this:
DO
... TerminatedStr = [String, 0], % String="foo" => [[$f, $o, $o], 0] port_command(Port, TerminatedStr) ...
Append example
DO
> lists:append([[1], [2], [3]]). [1,2,3] >
DO NOT
> lists:flatten([[1], [2], [3]]). [1,2,3] >
In the performance myth chapter, the following myth was exposed: .
To summarize, in R12B there is usually not much difference between a body-recursive list function and tail-recursive function that reverses the list at the end. Therefore, concentrate on writing beautiful code and forget about the performance of your list functions. In the time-critical parts of your code (and only there), measure before rewriting your code.
Important note: This section talks about lists functions that construct lists. A tail-recursive function that does not construct a list runs in constant space, while the corresponding body-recursive function uses stack space proportional to the length of the list. For instance, a function that sums a list of integers, should not be written like this
DO NOT
recursive_sum([H|T]) -> H+recursive_sum(T);recursive_sum([]) -> 0.
but like this
DO
sum(L) -> sum(L, 0).sum([H|T], Sum) -> sum(T, Sum + H);sum([], Sum) -> Sum.
转载地址:http://upxlf.baihongyu.com/