Steven D'Aprano <[EMAIL PROTECTED]> writes:

> On Sat, 04 Oct 2008 17:07:14 +0200, Martin Geisler wrote:
>
>> A somewhat related question: do I pay a performance penalty when I
>> let a function define an inner function like this:
>> 
>>   def foo():
>> 
>>     def bar()
>>       ...
>> 
>>     bar()
>> 
>> compared to just defining it once outside:
>> 
>>   def bar():
>>     ...
>> 
>>   def foo():
>>     ...
>>     bar()
>> 
>> I'm thinking that each execution of the first foo could spend a
>> little time defining a new bar each time, or is that not how things
>> work?
>> 
>> I realize that defining bar as an inner function has the advantage of
>> being able to see variables in the namespace of foo.
>
> That is the main advantage, followed by reducing namespace pollution,
> but yes there is a very small performance penalty.
>
>
>>>> def outer(x):
> ...     return x+1
> ...
>>>> def func(x):
> ...     return outer(x+1)
> ...
>>>>
>>>> def func2(x):
> ...     def inner(x):
> ...             return x+1
> ...     return inner(x+1)
> ...
>>>> assert func(37) == func2(37)
>>>> from timeit import Timer
>>>> t1 = Timer('func(23)', 'from __main__ import func')
>>>> t2 = Timer('func2(23)', 'from __main__ import func2')
>>>> t1.repeat()
> [1.5711719989776611, 0.82663798332214355, 0.82708191871643066]
>>>> t2.repeat()
> [1.8273210525512695, 1.1913230419158936, 1.1786220073699951]

Very interesting, thanks for measuring this!

-- 
Martin Geisler

VIFF (Virtual Ideal Functionality Framework) brings easy and efficient
SMPC (Secure Multi-Party Computation) to Python. See: http://viff.dk/.

Attachment: pgpLR7SBbBPVr.pgp
Description: PGP signature

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to