A performance issue when using default value

Chris Rebert clp2 at rebertia.com
Mon Feb 1 06:21:18 CET 2010


On Sun, Jan 31, 2010 at 8:58 PM, keakon <keakon at gmail.com> wrote:
> I've found strange performance issue when using default value, the
> test code is list below:
>
> from timeit import Timer
>
> def f(x):
>  y = x
>  y.append(1)
>  return y
>
> def g(x=[]):
>  y = []
>  y.append(1)
>  return y
>
> def h(x=[]):
>  y = x
>  y.append(1)
>  return y
>
> def f2(x):
>  y = x
>  y.append(1)
>  return y + []
>
> def g2(x=[]):
>  y = []
>  y.append(1)
>  return y + []
>
> def h2(x=[]):
>  y = x
>  y.append(1)
>  return y + []
>
> TIMES = 10000
> print Timer('f([])','from __main__ import f, g, h').timeit(TIMES)
> print Timer('g()','from __main__ import f, g, h').timeit(TIMES)
> print Timer('h([])','from __main__ import f, g, h').timeit(TIMES)
> print Timer('h()','from __main__ import f, g, h').timeit(TIMES)
> print Timer('f2([])','from __main__ import f2, g2, h2').timeit(TIMES)
> print Timer('g2()','from __main__ import f2, g2, h2').timeit(TIMES)
> print Timer('h2([])','from __main__ import f2, g2, h2').timeit(TIMES)
> print Timer('h2()','from __main__ import f2, g2, h2').timeit(TIMES)
>
>
> I tested it with Python 2.5.4, 2.6.4 and 3.1.1 on Windows XP, and get
> almost the same result:
> 0.00449247041174
> 0.00439608944712
> 0.00455867994396
> 0.00327471787615
> 0.00791581052899
> 0.00684919452053
> 0.00734311204357
> 0.30974942346
>
> h2() is about 42 times slower than h2([]), but h() is a litter faster
> than h([]).
>
> If change TIMES to 20000, other results are 2 times than before, but h2
> () is 4 times(about 1.2 sec) than before.
>
> Is there any tricks in it?

Are you aware of the following pitfall?:

>>> def foo(a=[]):
...     a.append(7)
...     return a
>>>
>>> print foo()
[7]
>>> print foo()
[7, 7]
>>> print foo()
[7, 7, 7]

i.e. the default argument is only evaluated once (when the function is
defined) and is then reused every call when the caller doesn't provide
a value.

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list