Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Writing better `getters': |NS_IF_ADDREF(*aResult = mMember);|

0 views
Skip to first unread message

Scott Collins

unread,
Feb 27, 2000, 3:00:00 AM2/27/00
to
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

This message describes a new more efficien, code-pattern that John
Bandhauer and I would like to see become the idiom in [XP]COM
`getters'. The rest of this message is a slightly edited explanation
I previously sent to a smaller distribution in email.


|NS_IF_ADDREF()| often appears at the end of `getters' in an
arrangement like this

// ...
*aResult = mMember;
NS_IF_ADDREF(*aResult);
return NS_OK;
}

As Brendan and John Bandhauer have pointed out, the compilers suck at
optimizing the multiple de-referencing of |aResult|, because of their
fear of aliasing. This problem exists even if |aResult| is declared
as a |T*&| instead of a |T**|. I modified |NS_IF_ADDREF| to better
help the compiler make this code-pattern efficient (in
non-|AddRef|/|Release| logging builds). The new implementation lets
people who are concerned about this optimization use

NS_IF_ADDREF(*aResult = mMember); // slightly more efficient

The old implementation of |NS_IF_ADDREF| forced the compiler to
dereference |aResult| three times in the course of executing the first
code sample in a non-logging build (4 times in a logging build). The
new implementation allows |aResult| to be dereferenced only once in
the second sample (and only twice in the first). |NS_ADDREF| needed
no modification to support this form.

The new form is not forced on you, however. If you prefer the
original form, by all means use it. The gain in code clarity may be
well worth the small cost of a few extra instructions in an otherwise
complicated piece of code. In a simple getter, I highly recommend the
newer optimized form, since I believe it will be clear in context ...
and I hope that it will become the idiom for getters.

See bug #27343

<http://bugzilla.mozilla.org/show_bug.cgi?id=27343>

for more information.

Hope this helps,
______________________________________________________________________
Scott Collins <http://ScottCollins.net>

-----BEGIN PGP SIGNATURE-----
Version: PGP Personal Privacy 6.0.2
Comment: get my key at <http://ScottCollins.net/#key>

iQA/AwUBOLnbQfGmojMuVn+fEQKlhQCgqfRXHBGHxLOfEnvFuvEGY39Mgv4AoJx9
poRft2zGS45Io7/zmfbRlwwE
=U651
-----END PGP SIGNATURE-----

0 new messages