Jim Langston wrote:
Which is more efficient (if either)
You might get more accurate results by measuring it, rather than asking
here. It depends on many properites of your class and how you use it
(do the constructor/destructor do anything, is it modified while being
used, etc.). Here is my test program:
#include <vector>
#include <numeric>
using namespace std;
class HugeObject: public vector<int> {
public:
HugeObject(): vector<int>(500 00) {}
};
void use(HugeObject& h)
{
int t = accumulate(h.be gin(),h.end(),0 );
srand(t);
}
int main(int argc, char* argv[])
{
vector<HugeObje ct> SomeVals(1000);
for(int i=0; i<1000; ++i) {
HugeObject h = SomeVals[i];
use(h);
}
}
Platform: Linux, celeron-500, enough RAM, gcc-3.4, -O9.
real 0m8.916s
user 0m5.408s
sys 0m3.315s
Move the HugeObject h declaration outside the loop:
real 0m8.732s
user 0m6.597s
sys 0m1.969s
(Less system time probably means it spent less time doing low-level
memory allocation, presumably because it allocated in larger chunks.
But it makes up for that with more user time, for some reason. The
overall difference is not significant.)
Put the declaration back inside the loop but make it a reference. You
can only do this if you are not going to modify the copy, or don't mind
SomeVal also being changed:
real 0m5.427s
user 0m3.348s
sys 0m1.948s
Somewhat better.
But none of these are really significant differences. If you are
worried about the efficiency of your application you should be looking
for big-O complexity reduction, not this sort of change.
--Phil.