[erlang-questions] Tail Call Optimization and Parameter Ordering
Rick Pettit
rpettit@REDACTED
Tue Nov 6 02:06:16 CET 2007
On Mon, Nov 05, 2007 at 06:18:47PM -0600, David Mercer wrote:
> James Hague in "A deeper look at tail recursion in Erlang"
> (http://prog21.dadgum.com/1.html) makes an interesting point about
> optimizing tail recursion by keeping parameters in the same order. This, I
> think, answers a question I have had in my mind about ordering parameters in
> functions in a module: is it better to put the main object at the beginning
> of the parameter list or the end?
>
>
>
> For example, suppose we have a module "widget" that implements some sort of
> widget--whatever that is--with a couple of member functions that act on a
> widget, say "change" and "query". Is it better to implement these functions
> with the widget object being the first parameter or the last? That is,
> which is better:
>
>
>
> change(Widget, Arg1, Arg2) -> .
>
> query(Widget, Arg1) -> .
>
>
>
> or:
>
>
>
> change(Arg1, Arg2, Widget) -> .
>
> query(Arg1, Widget) -> .
>
>
>
> Based on Hague's insight, I would say the former, with the object up front,
> is better. Why? Because functions that are used by these functions (and
> functions that use them) are likely to copy the pattern (in fact, they
> should), and the Widget argument can therefore fall through in the same
> position. For example, if change/3 has to call a couple of private
> functions in the module in order to perform the "change," it is likely these
> functions will have different arity. If we are in the habit of putting the
> object at the end of the parameter list, then its position will have
> changed. If, on the other hand, the object is at the beginning of the
> parameter list, it will always be in the same position and will cause less
> stack manipulation. Granted, this optimization only occurs in the case of
> tail calls, but surely this is a good habit to be in for that case when the
> tail call optimization can be used.
I don't know the answer regarding performance, but it seems clear that for
reasons of consistency alone one might want to always pass the Widget
as the first argument to all functions which operate on Widget.
-Rick
P.S. Perhaps others on the list could correct me but this might be an
instance where the 'clarify' topic would have been useful.
More information about the erlang-questions
mailing list