Version 3 of Interning a String

Updated 2006-09-20 23:08:30

>Strick> In some languages (eg [L1 ] ) you can "intern" a string, which gives you one unique "interned instance" of the string with that value. Here's a proc to do it in Tcl:

 proc intern s {
        if { ! [info exists ::INTERN($s)] } { set ::INTERN($s) $s }
        set ::INTERN($s)
 }

I used Tcl a dozen years before needing this, but today i wrote a program that used many of the same long strings (file pathnames) in some Tcl lists.

There's two different reasons you might want to intern a string:

  • To make string comparisons as fast as pointer comparisons
  • To save memory, when strings with the same value are used many times

Most often you intern strings for the first reason, but in Tcl that can't work: there are no separate "value" and "address" comparisons. Today I interned for the second reason.