[comp.sys.mac.programmer] Dereferencing handles

pete@ics.uci.edu (Peter Miguel Oleary) (12/20/89)

In article <9313@hoptoad.uucp> tim@hoptoad.UUCP (Tim Maroney) writes:
>In article <3331@hub.UUCP> 6500stom@hub.UUCP writes:
>>> I know this has been discussed before, but could someone tell me when
>>> it is necessary to use HLock?  If i have a handle within a CDEF do i need
>>> to do so?  What if i only access the handle thru a pointer, i.e. :
>>> 
>>> ControlPtr cp;
>>> cp = *theControl;
>>> if (cp->contrlRect ...... and so on.......
>>
>>It doesn't matter whether you dereference it or not in C.  You might
>>as well have done (**theControl).contrlRect instead of cp->contrlRect.
>
>Sort of.  I would never do this, and I strongly recommend against it.
>As soon as anything happens which could move memory, cp becomes an
>invalid pointer, and has to be refreshed from theControl.  It would be
>awfully easy to forget this; it's asking for errors which wouldn't happen
>if you always used (*theControl)-> instead of cp-> .

Actually, I do something like that all the time and wholeheartedly recommend
it, as long as you know what you are doing.  Why?  Because it is somewhat
difficult for a compiler to do optimization when you assign through a
handle using "(*x) -> y" or "(**x).y" and some compilers will generate
very poor code to handle (no pun) these statements.  So it is up to the
programmer to take control and force some optimizations, like so:

	register Ptr p;

	HLock(h);

	p = *h;
	p -> x = 1;
	p -> y = 2;

	...

	HUnlock(h);

What this does is do?  Assuming that p actually ends up in a register (some
very popular compilers will not put a variable into a register unless you
explicitly tell it to...) this little trick will save you one memory reference
and one indirection every time you reference through that handle.  This adds
up big time in terms of space and time used.  In some handle-referencing-
intensive functions, we're talking about a 100-200% savings.

Note that Pascal programmers don't need to do this: they have the "with"
statement to play with.  Pascal compilers will usually do something similar
to this automagically when you say "with h^^ do".

Pete O'Leary.