Re: Garbage collection for objects?
- To: mathgroup at smc.vnet.net
- Subject: [mg93467] Re: Garbage collection for objects?
- From: David Bailey <dave at removedbailey.co.uk>
- Date: Mon, 10 Nov 2008 03:29:50 -0500 (EST)
- References: <gf6drt$k28$1@smc.vnet.net>
Jochen Adamek wrote: > Hello, > > i would like to know, if it's possible to overwrite objects, which are > defined as parameters for functions? > > I made the experience, that you have to define a copy of this objects > to change values of them. > > I don't know how Mathematica manage these copies. Is there a method > like garbage collection? > > Shall i delete these objects manually? > > Best regards > > J.A. > First, it is usually not useful to think of Mathematica in terms of another language such as Java, because the relationship is not simple. Garbage collection is performed by reference counting, and is meant to be invisible to the user. You can modify a structure provided you reference it using the variable that has it as a value. For the sake of simplicity, let us assume that the structure that you want to modify is a list, and consider the following three functions and a global variable containing some data: In[2]:= foo1[ll_] := (ll[[2]] = 42); foo2[ll_] := Module[{tmp = ll}, tmp[[2]] = 42]; In[4]:= SetAttributes[foo3, HoldFirst]; foo3[ll_] := (ll[[2]] = 42); In[6]:= myList = {1, 2, 3, 4} Out[6]= {1, 2, 3, 4} The first version fails with an error because you are trying to modify an actual list: In[7]:= foo1[myList]; myList During evaluation of In[7]:= Set::setps: {1,2,3,4} in the part \ assignment is not a symbol. >> Out[8]= {1, 2, 3, 4} The second version does not generate an error, but modifies the contents of variable tmp - so there is no permanent effect. In[9]:= foo2[myList]; myList Out[10]= {1, 2, 3, 4} This version works and actually modifies the value of the global variable, because the HoldFirst attribute suppresses the evaluation of myList to its value - the actual variable gets passed as the argument. In[11]:= foo3[myList]; myList Out[12]= {1, 42, 3, 4} Clearly there are some fairly subtle things going on here. If you have a variable aaa whose value is a large list (say), then the list is not copied if you execute bbb=aaa However, if you subsequently modify the list held by bbb, a copy is taken so that the results are as if the system always performed a copy! David Bailey http://www.dbaileyconsultancy.co.uk