Version 1 of unshared value idiom

Updated 2015-03-14 13:57:16 by pooryorick

the unshared value idiom is a technique for unsharing a Tcl_Obj that so that Tcl doesn't have to copy it in order to modify it.

Description

Tcl stores a value in a Tcl_Obj, and when a value is passed as an argument to a command, that Tcl_Obj is bound to the corresponding variable in the scope of the command. If the Tcl_Obj is also bound to a variable in the caller, then it is shared, and unavailable to hold any new value the command may produce. On the other hand, it the Tcl_Obj is unshared, the command might be able to reuse that Tcl_Obj instead of creating a new one. For example, if the value of the Tcl_Obj is a large list and is unshared, a command like lappend might save a lot of time and memory by reusing that object.

So how does one go about making sure the Tcl_Obj that is passed to the command is unshared? The answer is rebind the variable holding the Tcl_Obj in the caller to some other value. One trick to accomplish this in one line is to set the variable to the empty string in a command substitution at the end of the value being passed:

somecommand $myvalue[set myvalue {}]

Since substituting the empty string is a no-op, the side effect of rebinding the variable to a new value is efficiently achieved.

Here's an lpop command which rebinds the variable to a useful string instead of binding to the empty string:

set item [lindex $list end]
set list [lreplace $list [set list end] end]

See Also

K
Presents various alternate wordings of the unshared value idiom