28/09/2008

Sometimes I 'get it' and sometimes I don't!

Today I was trying to free up some objects, so that they would garbage collect. What I tried to do was:

Fspace allInstancesDo:
[:each |
each := nil.
Transcript show: (each value); cr.
Smalltalk garbageCollect]

What I expected it to do was to set each of the instances to nil. Of course, as Randal kindly pointed out, it would do no such thing. What it actually does is set the value of the :each temporary variable, to nil.

I was thinking about why I had made that mistake and the conclusion I came to was that I was becoming so used to sending messages to objects, that I thought I was somehow communicating with the instance, rather than with the temporary variable.

Ah well, onwards and upwards :-)

2 comments:

Randal L. Schwartz said...

The problem is that := isn't a message send, except maybe to the VM.

It tells the VM "throw away the current value of the variable, and replace it with the computed value on the right side here". So any object already in the variable can never influence the result of the operation.

Once you understand that, you'll see why "each := nil" can't possibly do anything to the existing value of "each".

Andy Burnett said...

Your timing is superb. I was cleaning my teeth, pondering what I had learned on the beginners' list, when I suddenly thought "why isn't := sent to the object referenced by :each, when other message sends would be"? And, with that, my iPhone went 'boing' and the answer arrived!

Brilliant :-)
TVM