博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
lists优化,尾递归的重要一点
阅读量:2058 次
发布时间:2019-04-29

本文共 2070 字,大约阅读时间需要 6 分钟。

lists优化,尾递归的重要一点

 builds an entirely new list. Therefore, it is expensive, and even more 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  or .
  • When you know that your list is only one level deep, you can can use .

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/

你可能感兴趣的文章
单元测试需要具备的技能和4大阶段的学习
查看>>
【Loadrunner】【浙江移动项目手写代码】代码备份
查看>>
Python几种并发实现方案的性能比较
查看>>
[Jmeter]jmeter之脚本录制与回放,优化(windows下的jmeter)
查看>>
Jmeter之正则
查看>>
【JMeter】1.9上考试jmeter测试调试
查看>>
【虫师】【selenium】参数化
查看>>
【Python练习】文件引用用户名密码登录系统
查看>>
学习网站汇总
查看>>
【Python】用Python打开csv和xml文件
查看>>
【Loadrunner】性能测试报告实战
查看>>
【面试】一份自我介绍模板
查看>>
【自动化测试】自动化测试需要了解的的一些事情。
查看>>
【selenium】selenium ide的安装过程
查看>>
【手机自动化测试】monkey测试
查看>>
【英语】软件开发常用英语词汇
查看>>
Fiddler 抓包工具总结
查看>>
【雅思】雅思需要购买和准备的学习资料
查看>>
【雅思】雅思写作作业(1)
查看>>
【雅思】【大作文】【审题作业】关于同不同意的审题作业(重点)
查看>>