efficient way to copy composite types
I'm perusing code that is structured around - presumably a bridge design. There's performance concerns surround the store functions that store composite types which contains POD types. So consider:
Code:
# include <iostream>
# include <iomanip>
struct foo {
int x ;
int y ;
// more stuff
};
struct bar {
foo f;
void store ( const foo& in )
{ f = in; }
};
int main()
{
foo f ;
bar b;
b.store ( f ) ;
}
For starters, there was a discussion about using std::swap to copy the structs ( though admittedly I'm not following how) or memcpy. While I haven't had a chance to benchmark a memcpy version, I question what this will 'buy' me. Thoughts/suggestions
Thanks in advance
Re: efficient way to copy composite types
I think swap will be more efficient than memcpy for smaller objects because it does not use a loop. For bigger objects, locality of reference will make memcpy execute faster.
Re: efficient way to copy composite types
Quote:
Originally Posted by
mop65715
I'm perusing code that is structured around - presumably a bridge design. There's performance concerns surround the store functions that store composite types which contains POD types. So consider:
Code:
# include <iostream>
# include <iomanip>
struct foo {
int x ;
int y ;
// more stuff
};
struct bar {
foo f;
void store ( const foo& in )
{ f = in; }
};
int main()
{
foo f ;
bar b;
b.store ( f ) ;
}
For starters, there was a discussion about using std::swap to copy the structs ( though admittedly I'm not following how) or memcpy. While I haven't had a chance to benchmark a memcpy version, I question what this will 'buy' me. Thoughts/suggestions
Thanks in advance
What you have here are PODs (Plain old data), and your compiler should be quite efficient at seeing that. You can trust your compiler to use the BEST copy method available when you write myFoo = iFoo.
In my opinion, doing anything else but the default provided operator= can only lower your efficiency.
To copy stuff using swap uses a compiler optimization called "Copy-and-swap" (http://en.wikibooks.org/wiki/More_C%.../Copy-and-swap). Chances are that with the release of C++0x, it will be changed to copy-and-move.
But you need to realize that the above swap methods work you have pointer to data objects. It doesn't really work with PODs.
Re: efficient way to copy composite types
Isn't memcpy usually implemented via duffs device? If so, no loop there either!