Function application optimization.

John Roth newsgroups at jhrothjr.com
Fri Dec 12 08:45:44 EST 2003


"Jacek Generowicz" <jacek.generowicz at cern.ch> wrote in message
news:tyf7k128j09.fsf at pcepsft001.cern.ch...
> Given
>
>   fncs = [func1, func2, ..., funcN]
>   args = [arg1,  arg2,  ..., argN]
>
> How should one spell
>
>   results = map(lambda f,a: f(a), fncs, args)
>
> in order to get the result most quickly ?
>
>
>
> Unfortunately "apply" takes a tuple of arguments, and there is no
> "funcall"[*] in Python.
>
>
> [*] def funcall(fn, *args):
>         return fn(*args)


Building on a couple of other responses:

Untested code:

fncs = [func1, func2, ..., funcN]
args = [arg1,  arg2,  ..., argN]
results = []
for function, arguement in zip(fncs, args):
    results.append(function(arguement))

Notice the use of zip() to put the two lists together.
I haven't timed it, but removing an extra layer of
function call has got to be faster. Likewise, zip
and tuple unpacking is most likely going to be
faster than indexing every time through the loop.
The append, on the other hand, might slow things
down a bit.

John Roth

>






More information about the Python-list mailing list