[Python-ideas] Fast sum() for non-numbers
Ronald Oussoren
ronaldoussoren at mac.com
Tue Jul 9 16:00:59 CEST 2013
On 9 Jul, 2013, at 15:54, Sergey <sergemp at mail.ru> wrote:
> On Jul 9, 2013 Steven D'Aprano write:
>
>>> Well... Yes, I can! I can't make __iadd__ faster, because tuple has
>>> no __iadd__, however I can make a faster __add__.
>>
>> And how do you expect to do that? Tuples are immutable, you have
>> to create a new tuple. So when adding a sequence of N tuples
>> together, you end up making and throwing away N-1 intermediate
>> results.
>
> For example, rewrite tuple to internally store its values in a list,
> and have `localcount` variable saying how many items from that list
> belong to this tuple. Then __add__ could extend that list and reuse
> it for new tuple.
That's not going to happen, not only breaks that backward compatibility
for users for the C API, it has nasty side effects and is incorrect.
Nasty side effect:
a = (1,)
b = (2,) * 1000
c = a + b
del b
del c
With the internal list 'a' keeps alive the extra storage used for 'c'.
Incorrect:
a = (1,)
b = a + (2,)
c = a + (3,)
Now 'b' and 'c' can't possibly both share storage with 'a'.
Ronald
More information about the Python-ideas
mailing list