`
ZacMa
  • 浏览: 38933 次
  • 来自: 深圳
社区版块
存档分类
最新评论

<16>Efficiency Guide之Common Caveats

阅读更多
(1) ++
如果做一个list的反转,不要这样,

naive_reverse([H|T]) ->
    naive_reverse(T)++[H];
naive_reverse([]) ->
    [].
因为这样, ++左边的列表会被一次次的拷贝,结果出现相当复杂的操作,
Since the ++ operator copies its left operand, the result will be copied again and again and again... leading to quadratic complexity.
lists.erl模块中的append/1也是用++实现,使用时候,列表不可以过长


要这样:
naive_but_ok_reverse([H|T], Acc) ->
    naive_but_ok_reverse(T, [H]++Acc);
naive_but_ok_reverse([], Acc) ->
    Acc.
这样增长的列表在右边,不会被拷贝,所以每个元素拷贝一次,即可完成
Each list element will only be copied once. The growing result Acc is the right operand for the ++ operator, and it will not be copied.


2 timer使用
timer使用,最好使用erlang模块中的send_after/3和erlang:start_timer/3,timer模块是用单独的进程管理timer,如果频繁的创建或者取消,很容易使进程超负荷,尤其是使用smp时候,但是其中的tc,sleep等函数和管理进程无关的,无影响
Creating timers using erlang:send_after/3 and erlang:start_timer/3 is much more efficient than using the timers provided by the timer module. The timer module uses a separate process to manage the timers, and that process can easily become overloaded if many processes create and cancel timers frequently (especially when using the SMP emulator).

The functions in the timer module that do not manage timers (such as timer:tc/3 or timer:sleep/1), do not call the timer-server process and are therefore harmless.

3  list_to_atom慎用,因为不参与系统回收,系统的atom有数量限制,如果可用
list_to_existing_atom;
文档原文:
Atoms are not garbage-collected. Once an atom is created, it will never be removed. The emulator will terminate if the limit for the number of atoms (1048576 by default) is reached.

Therefore, converting arbitrary input strings to atoms could be dangerous in a system that will run continuously. If only certain well-defined atoms are allowed as input, you can use list_to_existing_atom/1 to guard against a denial-of-service attack. (All atoms that are allowed must have been created earlier, for instance by simply using all of them in a module and loading that module.)

Using list_to_atom/1 to construct an atom that is passed to apply/3 like this

apply(list_to_atom("some_prefix"++Var), foo, Args)


4 length/1另用法,更快速的用法, 因为length/1不同于tuple_size/1, byte_size/1, and bit_size/1这些函数,他的时间和列表成正比例,
原文
The time for calculating the length of a list is proportional to the length of the list, as opposed to tuple_size/1, byte_size/1, and bit_size/1, which all execute in constant time.

Normally you don't have to worry about the speed of length/1, because it is efficiently implemented in C. In time critical-code, though, you might want to avoid it if the input list could potentially be very long.

Some uses of length/1 can be replaced by matching. For instance, this code

foo(L) when length(L) >= 3 ->
    ...
can be rewritten to

foo([_,_,_|_]=L) ->
   ...
(One slight difference is that length(L) will fail if the L is an improper list, while the pattern in the second code fragment will accept an improper list.)

5  setelemeng/3的使用要注意,不要在大的循环中用来全部代替,如果要用,最优的方案是满足一些条件,否则先把tuple转化成list再使用,  原文:
3.4  setelement/3

setelement/3 copies the tuple it modifies. Therefore, updating a tuple in a loop using setelement/3 will create a new copy of the tuple every time.

There is one exception to the rule that the tuple is copied. If the compiler clearly can see that destructively updating the tuple would give exactly the same result as if the tuple was copied, the call to setelement/3 will be replaced with a special destructive setelement instruction. In the following code sequence

multiple_setelement(T0) ->
    T1 = setelement(9, T0, bar),
    T2 = setelement(7, T1, foobar),
    setelement(5, T2, new_value).
the first setelement/3 call will copy the tuple and modify the ninth element. The two following setelement/3 calls will modify the tuple in place.

For the optimization to be applied, all of the followings conditions must be true:

The indices must be integer literals, not variables or expressions.
The indices must be given in descending order.
There must be no calls to other function in between the calls to setelement/3.
The tuple returned from one setelement/3 call must only be used in the subsequent call to setelement/3.
If it is not possible to structure the code as in the multiple_setelement/1 example, the best way to modify multiple elements in a large tuple is to convert the tuple to a list, modify the list, and convert the list back to a tuple.

6 用  tuple_size/1 或者 byte_size/1 而不是size,
原文:
3.5  size/1

size/1 returns the size for both tuples and binary.

Using the new BIFs tuple_size/1 and byte_size/1 introduced in R12B gives the compiler and run-time system more opportunities for optimization. A further advantage is that the new BIFs could help Dialyzer find more bugs in your program.

7
优先使用,模式匹配,而不是,split_binary, 在二进制处理程序中,
split_binary/2

It is usually more efficient to split a binary using matching instead of calling the split_binary/2 function. Furthermore, mixing bit syntax matching and split_binary/2 may prevent some optimizations of bit syntax matching.

DO

        <<Bin1:Num/binary,Bin2/binary>> = Bin,
DO NOT

        {Bin1,Bin2} = split_binary(Bin, Num)

8
关于--
Note that the '--' operator has a complexity proportional to the product of the length of its operands, meaning that it will be very slow if both of its operands are long lists:
Using the '--' operator to delete an element from a list is not a performance problem:

OK
        HugeList1 -- [Element]
分享到:
评论

相关推荐

    iTunes-2-FileMaker:将 iTunes 库 XML 转换为 FileMaker FMPXMLRESULT

    iTunes-2-FileMaker 将 iTunes 库 XML(元数据)转换为 FileMaker XML (FMPXMLRESULT) 的 PHP 脚本##用法运行php itunes2filemaker.php &lt;iTunes&gt; [&lt;output&gt;]然后可以将生成的 XML 文件导入 FileMaker。 ##...

    homebrew-caveats:Homebrew软件包管理器的公式警告捷径

    Homebrew软件包管理器的公式警告捷径 它是什么? 这是的。 它提供了有关Homebrew软件包和酒桶的安装说明。 用法 虽然脚本的名称是brew-caveats.rb和brewcask-...==&gt; zsh: Caveats Add the following to your zshrc to

    vxworks_kernel_programmers_guide_6.9

    Kernel Programmer's Guide, 6.9 iv Inconsistent Cache Mode Support .................................................................. 17 System Viewer Instrumentation Support .............................

    Improving API CAveats Accessibility by Mining Caveats Knowledge Graph

    然而,API注意事项往往分散在多个文档中,并且隐藏在冗长的文本描述之中,这使得开发者难以发现这些重要的注意事项。当开发者未能注意到这些注意事项时,很可能会导致意外的编程错误。 #### 研究方法与目标 为了...

    OTA 资料分享,好用的资料

    OTA,全称Over-the-Air Technology,是一种无线通信技术,主要用于软件更新和数据传输。在IT行业中,OTA尤其被广泛应用于移动设备,如智能手机、平板电脑以及智能电视等物联网设备。这种技术允许用户通过无线网络...

    nvim-lua-guide-zh:https

    Caveats Vim 命名空间 Tips 在 Lua 中使用 Vimscript vim.api.nvim_eval&#40;&#41; Caveats vim.api.nvim_exec&#40;&#41; vim.api.nvim_command() Tips 管理 vim 的设置选项 使用 api 函数 使用元访问器 Caveats ...

    Learn SpriteBuilder for iOS Game Development

    In this book, you will learn SpriteBuilder...Along the way, I’ll explain the SpriteBuilder features, caveats, workarounds, and helpful tips and tricks as you are most likely to come across or need them.

    MapReduce Design Pattern

    Each pattern is explained in context, with pitfalls and caveats clearly identified to help you avoid common design mistakes when modeling your big data architecture. This book also provides a complete...

    关于pandas一些warning的解决办法

    See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy df_1_level['level1_name'] = df_1_level['department_name'] ...

    Cisco ISP Essentials

    **Interface Configuration**: This section covers descriptions, bandwidth, IP unnumbered, caveats, and provides a full example of interface configuration. **Interface Status Checking**: The guide ...

    BobBuilder_app

    Twitter Digg Facebook Del.icio.us Reddit Stumbleupon Newsvine Technorati Mr....Database » Database » Other databasesLicence CPOL ...Even faster Key/Value store nosql embedded database ...

    [ZooKeeper] ZooKeeper 开发编程 (英文版)

    This practical guide shows how Apache ZooKeeper helps you manage distributed systems, so you can focus mainly on application logic. Even with ZooKeeper, implementing coordination tasks is not trivial...

    EDFA仿真代码.zip

    Some CAVEATS are in order. 1. This solution does NOT incorporate ASE or strong-signal saturation effects. Therefore if you are interested in high-gain (&gt;20 dB) or high-power (&gt;100 uW input) ...

    Training Neural Networks without Gradients

    including batch methods, suffers from common problems like saturation effects, poor conditioning, and saddle points. This paper explores an unconventional training method that uses alternating ...

    Professional.MFC.with.VC6

    Chapter 16: ActiveX Controls Looking at the User Interface The Birth of Custom Controls Custom Controls: The Next Generation The Fundamentals of ActiveX Controls Controls at Run Time Creating a ...

    Internet Traffic classification demystified

    互联网流量分类是一个在互联网研究与实际应用中至关重要的领域,涉及到对不同类型的网络流量进行识别和管理。随着互联网应用的不断扩展,对流量进行有效分类的需求日益增长,这不仅关系到网络运营的效率,还涉及到...

    windows 32位和64位 Erlang 21.0.1下载

    This guide covers Erlang/OTP requirements, recommendations, caveats and commonly used installation sources. Unsupported Versions Erlang/OTP versions older than 19.3 are not supported by currently ...

Global site tag (gtag.js) - Google Analytics