Re: By Reference
- To: mathgroup at smc.vnet.net
- Subject: [mg105414] Re: By Reference
- From: Albert Retey <awnl at gmx-topmail.de>
- Date: Tue, 1 Dec 2009 06:27:47 -0500 (EST)
- References: <hf2mrq$ie9$1@smc.vnet.net>
Hi, > > I am implementing a "call by reference" in Mathematica using HoldFirst > in order to send a huge matrix into a function. > > I wanted to verify that Mathematica doesn't create a memory copy of > this matrix once it is being sent to the function. To verify that no copy has been made, you can use: MemoryInUse[] before and after the call. Note that Mathematica will usually only make copies of objects when they are changed ("copy on write"). So if you only read and don't change the matrix, you wouldn't even need the HoldFirst. On the other hand, there are situations when a copy is made despite of the HoldFirst attribute, e.g.: Clear[mat1, mat2]; mem1 = MemoryInUse[]; mat1 = RandomReal[{0, 1}, {1000, 1000}]; mem2 = MemoryInUse[]; mem2 - mem1 mem1 = MemoryInUse[]; mat2 = mat1; mem2 = MemoryInUse[]; mem2 - mem1 SetAttributes[h, HoldFirst] h[m_] := m[[1, 1]] = 10. mem1 = MemoryInUse[]; h[mat1]; mem2 = MemoryInUse[]; mem2 - mem1 mat1[[1, 1]] mat2[[1, 1]] in the above example you will find that the definition mat2=mat1 will not make a copy, no extra memory is used, both mat1 and mat2 point to the same "block of memory". But after redefining mat1[[1,1]] you will note that mat2 still has the original value in mat2[[1,1]], and from MemoryInUse you can guess that now a copy has been made. Without the definition mat2=mat1 no copy happens when mat[[1,1]] is redefined and no extra memory will be used. So if you want to make sure to be memory efficient, you will need to make sure not to fall into traps like this... hth, albert