Version 0 of unshared value idiom

Updated 2014-11-21 01:06:46 by pooryorick

the unshared value idiom is a technique for unsharing a value 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, the same Tcl_Obj is simply bound to the variable represents that argument in the scope of the command. if the value is then modified during the evaluation of the command, Tcl must store the modified value into a Tcl_Obj. This often means creating a new Tcl_Obj to hold the modified value. However, if the Tcl_Obj that held the original value is marked as unshared, Tcl can skip the step of creating a new Tcl_Obj, and instead discard the original value and store the new value into the original Tcl_Obj.

So how does one go about making sure the Tcl_Obj that is passed to the command is unshared? The answer is to set the value of the Tcl_Obj to the empty string while at the same time passing it to the command:

somecommand $myvalue[set myvalue {}]

And that is the unshared value idiom, the various alternate wordings of which appear on the page for K.