Download Erlang/OTP System Documentation
Transcript
7.6 Functions [Map(X, Y)|map_pairs1(Map, Xs, Ys)]. The first argument is not a problem. It is variable, but it is a variable in all clauses. The problem is the variable in the second argument, Xs, in the middle clause. Because the variable can match anything, the compiler is not allowed to rearrange the clauses, but must generate code that matches them in the order written. If the function is rewritten as follows, the compiler is free to rearrange the clauses: DO map_pairs2(_Map, [], Ys) -> Ys; map_pairs2(_Map, [_|_]=Xs, [] ) -> Xs; map_pairs2(Map, [X|Xs], [Y|Ys]) -> [Map(X, Y)|map_pairs2(Map, Xs, Ys)]. The compiler will generate code similar to this: DO NOT (already done by the compiler) explicit_map_pairs(Map, Xs0, Ys0) -> case Xs0 of [X|Xs] -> case Ys0 of [Y|Ys] -> [Map(X, Y)|explicit_map_pairs(Map, Xs, Ys)]; [] -> Xs0 end; [] -> Ys0 end. This is slightly faster for probably the most common case that the input lists are not empty or very short. (Another advantage is that Dialyzer can deduce a better type for the Xs variable.) 7.6.2 Function Calls This is an intentionally rough guide to the relative costs of different calls. It is based on benchmark figures run on Solaris/Sparc: • • • Calls to local or external functions (foo(), m:foo()) are the fastest calls. Calling or applying a fun (Fun(), apply(Fun, [])) is about three times as expensive as calling a local function. Applying an exported function (Mod:Name(), apply(Mod, Name, [])) is about twice as expensive as calling a fun or about six times as expensive as calling a local function. Notes and Implementation Details Calling and applying a fun does not involve any hash-table lookup. A fun contains an (indirect) pointer to the function that implements the fun. Ericsson AB. All Rights Reserved.: Erlang/OTP System Documentation | 235