Version 2 of Fixing Tk_Uid leaks

Updated 2007-12-25 02:45:57 by GPS

Richard Suchenwirth 2007-10-09 Why does Tcl leak memory? As explained on that page, Tk_Uids are created for text and canvas tags and never released. In a long running process, which on a canvas displays images and bounding boxes (polygons), I saw memory rise from 65MB to over 400 MB after some hours. Fixes as suggested by dkf:

  • reuse the displayed image: don't do each time
 $c create image 0 0 -image $im -anchor nw
 ...
 $c delete all

but create and display the image once, and reconfigure it with

 $im copy $im2 -shrink
  • reuse polygons by caching them in a global array g:
        if {![info exists g(of$n)]} {
            set id [$w create poly $coords -fill {} -outline $color -tag "xx of$n"]
            set g(of$n) $id
        } else {
            set id $g(of$n)
            $w coords $id $coords
            $w itemconfigure $id -outline $color
            $w raise $id
        }

and instead of deleting them, just move them "out of sight"

   foreach i [$w find withtag xx] {$w coords $i -100 -100 -99 -99}

George Peter Staplin Dec 24, 2007 - Does anyone have an interest in replacing Tk_Uids with some sort of Tcl_Obj or Tcl_Obj-like structure with reference counts for the 8.6 release? As I don't use the canvas widget much, the leaks don't bother me much, and I'm working on replacing Tk anyway with NexTk. Tk_Uids are definitely a design wart that should be fixed, if only for the legacy apps. I don't think it would even require a TIP of any kind, because it's a serious bug/design fix.

George Peter Staplin Every color on a canvas results in a Tk_Uid, so if you use a lot of random colors, you'll see the memory usage increase for every unique color.


Category performance