Getting around immutable default arguments for recursion
Steven D'Aprano
steven at REMOVE.THIS.cybersource.com.au
Wed Jan 14 21:02:57 EST 2009
On Wed, 14 Jan 2009 15:27:01 -0800, dpapathanasiou wrote:
>> a) a global should and need not be used.
>
> Passing the entire dictionary to every function that accesses it is
> better?
Yes. There is very little overhead when passing objects to functions in
Python. There's no performance penalty to passing objects instead of
relying on globals, and it may in fact be marginally faster:
>>> D = {'parrot': None}
>>>
>>> def byargument(d):
... return d
...
>>> def byglobal1():
... return D
...
>>> def byglobal2():
... global D
... return D
...
>>>
>>> from timeit import Timer
>>> setup = "from __main__ import byargument, byglobal1, byglobal2, D"
>>> t1 = Timer('result = byargument(D)', setup)
>>> t2 = Timer('result = byglobal1()', setup)
>>> t3 = Timer('result = byglobal2()', setup)
>>>
>>> min(t1.repeat())
0.23665285110473633
>>> min(t2.repeat())
0.23789191246032715
>>> min(t3.repeat())
0.23757314682006836
--
Steven
More information about the Python-list
mailing list