lists优化,尾递归的重要一点
来源:互联网 发布:岳飞十二道金牌知乎 编辑:程序博客网 时间:2024/06/10 03:58
lists优化,尾递归的重要一点
lists:flatten/1 builds an entirely new list. Therefore, it is expensive, and evenmore expensive than the ++ (which copies its left argument, but not its right argument).
In the following situations, you can easily avoid calling lists:flatten/1:
- When sending data to a port. Ports understand deep lists so there is no reason to flatten the list before sending it to the port.
- When calling BIFs that accept deep lists, such as list_to_binary/1 oriolist_to_binary/1.
- When you know that your list is only one level deep, you can can use lists:append/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: Tail-recursive functions are MUCH faster than recursive functions.
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.
- lists优化,尾递归的重要一点
- 递归的一点思考
- js递归的优化(尾递归)
- 关于递归的点一点
- 对递归的一点理解
- 关于icegrid的一点重要理解
- js对象比较重要的一点
- 关于函数调用和尾递归的一点认识
- 函数调用和尾递归的一点认识
- elasticsearch三个重要的优化
- elasticsearch三个重要的优化
- 递归优化之尾递归
- 递归及尾递归优化
- 递归及尾递归优化
- 递归优化之尾递归
- 浅谈尾递归的优化方式
- 快速排序的尾递归优化
- 浅谈尾递归的优化方式
- UVA 11806 Cheerleaders
- 位域的使用
- POJ 3468 线段树 区间更新区间查询
- java中split的使用
- Creo中替换装配中的某元件后,检入装配时依然收集该元件
- lists优化,尾递归的重要一点
- MFC CToolTipCtrl 总是显示
- 题目1046:求最大值
- IOS沙盒详解
- 第一章 Django简介
- 计算机是怎样工作的
- HDU 1501 Zipper
- JAVA对象排序之获取最小负载数
- 项目问题