From: Barry Margolin
Subject: Re: using closures for optimization
Date: 
Message-ID: <5uk84h$gi3@tools.bbnplanet.com>
In article <·············@wintermute.eagle>,
SDS  <···········@cctrading.com> wrote:
>And yet another simple technical question from a novice.
>
>I have a do loop to be executed about 2000 times. In it, I will be doing
>the same simple thing several times, and calling functions that do that
>too. Currently I have this:
>
>(defun main (foo)
>  (do ((adder #'(lambda (zz) (+ zz foo)))
>       (num 0 (1+ num)))
>      ((< num 2000))
>     (funcall adder num)
>     (bar adder num)))
>
>bar calls adder as (funcall adder zzz).
>Do I lose any performance by using the closure instead of just passing
>foo aroung? How much? Should I compile it?
>(the actual function in question has some multiplications, additions and
>slot accesses.)

Closures usually have a small performance impact, since all accesses to FOO
from the closure body have to indirect through an environment object.
However, there's also a performance impact in passing FOO as an argument to
BAR.  The difference will depend on the number of times the closure
references the free variables; if it just references it once as in the
above example, it probably doesn't matter what you do.  If it references it
many times, it may be better to pass it as an argument.  However, if the
closure only reads FOO and never modifies it, a good optimizing compiler
may be able to copy its value into a temporary, to avoid the indirection
overhead, so again the performance difference should be minimal.  The only
real way to find out in a particular implementation is to benchmark it.

The answer to your last question is: yes, always compile if performance is
a concern.

-- 
Barry Margolin, ······@bbnplanet.com
GTE Internetworking, Powered by BBN, Cambridge, MA
Support the anti-spam movement; see <http://www.cauce.org/>
Please don't send technical questions directly to me, post them to newsgroups.