[Python-Dev] possible Tkinter speedup

Fredrik Lundh Fredrik Lundh" <effbot@telia.com
Fri, 16 Jun 2000 18:41:36 +0200


the _flatten method in Tkinter is one of the major performance
bottlenecks for Python/Tk programmers.  the method "flattens"
a nested sequence, by repeatedly adding tuples to each other.

obviously, this isn't very efficient if the sequences are longer
than, say, five to ten items...  and has of course led to claims
like "wxPython is a thousand times faster than Tkinter".

anyway, taking recent changes to Python into account, it should
be possible to speed this up quite a bit.

the old code looked like this:

    def _flatten(tuple):
        res =3D ()
        for item in tuple:
            if type(item) in (TupleType, ListType):
                res =3D res + _flatten(item)
            elif item is not None:
                res =3D res + (item,)
        return res

after a some trials and errors, here's my proposed replacement:

    def _flatten1(seq):
        res =3D []
        for item in seq:
            if type(item) in (TupleType, ListType):
                res.extend(_flatten1(item))
            elif item is not None:
                res.append(item)
        return res
   =20
    def _flatten(seq):
        return tuple(_flatten1(seq))

in my tests, this is slighly faster on very short sequences (two
coordinate pairs, which is a common case for e.g. rectangles),
and much faster on long sequences (polylines, polygons).

for example, for a 5000-point line, it's about 15 times faster.
on a 10,000 point line, it's over 50 times faster.  etc.

comments?

can anyone come up with an even faster way to do this?

if I don't hear anything negative, I'll post patches (etc)

</F>

PS. even after this optimization, uiToolkit is still about 100 times
faster than Tkinter, but that's another story ;-)