Article View: alt.comp.lang.learn.c-c++
Article #776Re: Fast acces to class method
From: Tom
Date: Wed, 22 Mar 2000 00:00
Date: Wed, 22 Mar 2000 00:00
97 lines
2926 bytes
2926 bytes
On Wed, 22 Mar 2000 16:28:19 +0100, dataman@cyberdude.com wrote:
>What is the fastest way for accessing a member in a class.
>
>DATA is a structure;
>
>class A
>{
> public:
> //directly by having access to the member ?
> DATA data;
>
> //by return value
> DATA GetData()
> {
> return data;
> }
Does a copy of the structure, which could be slow if DATA is big.
>
> //by reference
> void GetData(DATA& d)
> {
> d=data;
> }
This time you are assigning, which is equally slow.
>
> //by pointer
> void GetData(DATA* pD)
> {
> *pData=data;
> }
Again, assigning.
[SNIP]
If you don't need to change DATA, but simply access it, then do:
const DATA& getData() const
{
return data;
}
If you want to change it, then do:
DATA& getData()
{
return data;
}
These break encapsulation, however. Consider changing DATA to a class,
rather than a struct.
Inline accessor methods returning references typically have zero
overhead compared to direct access, provided that they are not both
virtual and called through a pointer to A.
to access it, do
A a;
a.getData().member = x;
or
const A a;
x = a.getData().member;
or better:
void useData(const DATA& data)
{
//draw (data.member);
//etc;
}
useData(a.getData());
Finally, before writing a game in C++, I would consider reading some
books such as The C++ Programming Language, by Stroustrup, and Design
Patterns, by Gamma etc. This could save you time later, by telling you
how to design it properly, and how to use the features of C++ to
maximise performance. Trying a big project before you understand
design and some of the more interesting C++ features (templates, the
standard library, performance issues) will result is you exclaiming
"Damn, if only I'd waited till I knew about feature x!" at several
points in the future.
With C++ and a bit of know how, you can produce very fast software
that is properly object oriented.
Tom
Technical Details
Message-ID:
<38d904e5.5096852@news.demon.co.uk>Path:
arc1-ca.pugleaf.net!unknown!not-for-mailReferences:
<38D8E693.34731AA0@cyberdude.com>Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: 109fba,d558f056865fc0f1 X-Google-Attributes: gid109fba,public X-Google-Thread: 114592,d558f056865fc0f1 X-Google-Attributes: gid114592,public X-Google-Thread: fdcad,d558f056865fc0f1 X-Google-Attributes: gidfdcad,public From: rhinoceros1@hotmail.com (Tom) Subject: Re: Fast acces to class method Date: 2000/03/22 Message-ID: <38d904e5.5096852@news.demon.co.uk> X-Deja-AN: 600939387 X-NNTP-Posting-Host: cenes.demon.co.uk:194.222.206.118 References: <38D8E693.34731AA0@cyberdude.com> X-Trace: news.demon.co.uk 953747993 nnrp-02:9328 NO-IDENT cenes.demon.co.uk:194.222.206.118 Newsgroups: alt.comp.lang.learn.c-c++,comp.lang.c++,fr.comp.lang.c++ X-Complaints-To: abuse@demon.net