I have a basic question regarding memory management in TCL.
-
Suppose I have a Tcl procedure. Inside the procedure I declare an array and add some data in it. I do some number crunching on that array. My question is before the procedure returns do I need to manually delete the array? Using:
unset <array_name>My answer is no. But I am not sure since I don’t know if there is a garbage collector in Tcl. Can anyone comment on this please.
-
Is using array in Tcl bad? I want to create Array of lists and while reading discussions on stack overflow people told to use dict for these kind of stuff but since I have Tcl 8.4 I can’t. What is the problem with arrays in Tcl?
No. It will be deleted when the procedure returns (i.e., its lifespan is bounded to that of the stack frame). You may
unsetit earlier if you wish, which will free up its memory then, but you don’t need to do that.Arrays are absolutely fine in 8.4, so long as you remember that they are a collection that implements a map from arbitrary string keys to variables. Dicts are for cases where you want a value that holds a map from strings to arbitrary values. (There’s a dict extension for 8.4 somewhere about.) You can use arrays to model matrices by choosing some character as a separator between the sub-indices (e.g., a comma) and this technique has been used by many people to great effect.
However it is more efficient to model them as lists of lists; the
lsetand multi-indexlindexpermit efficient update and lookup of elements of the resulting matrix. (It is a bit verbose though.) If you’re dealing with a lot of data, the improved efficiency can be very useful. (Sparse matrices may be better done as a Tcl array despite that.) Also note that if you can upgrade to 8.5, a number of operations there are significantly faster (notably including testing for the presence of an element of an array withinfo exists).