A performance issue when using default value
alex23
wuwei23 at gmail.com
Mon Feb 1 00:16:43 EST 2010
keakon <kea... at gmail.com> wrote:
> def h2(x=[]):
> y = x
> y.append(1)
> return y + []
> h2() is about 42 times slower than h2([]), but h() is a litter faster
> than h([]).
Are you aware that 'y = x' _doesn't_ make a copy of [], that it
actually points to the same list as x?
My guess is that the slowdown you're seeing is due to the increasing
size of x _per timing iteration_. h2([]) will pass a new list each
time, while h2() will append to the same list _every_ time. The
difference between h & h2 is due to the concatenation of a new list to
the built one: the longer the default list grows, the longer this will
take, as extending a list takes O(k) time, with k being the number of
elements.
More information about the Python-list
mailing list