Fixing Tk_Uid leaks

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.

KBK My personal opinion is every use of Tk_Uid is a bug. If someone had the energy to replace Tk_Uid with something else for colors, or fonts, or tags, or whatever, the changes could even be bundled in a patch release. This is not a case where the TCT is obstructing the work; it's just a whale of a lot of work, and most of us have been concentrating on other things. It's also not a single project. Each use of Tk_Uid could be addressed separately.

John once told me that he considered Tk_Uid to be his single biggest mistake in the design of Tk.