While developing a message-driven system we’ve come to a problem of what type of object creation/destruction uses less system resources: stack or heap. And although you maybe know the answer it’s always interesting to measure to be sure. We’ve done it with the help of unit-testing.
First a test object have been created:
class TestObject { public: explicit TestObject(vector a, vector b) : mv1(a), mv2(b) { } vector mv1; vector mv2; };
Another version of test object is using const reference for parameters:
class TestObject { public: explicit TestObject(const vector &a, const vector&b) : mv1(a), mv2(b) { } vector mv1; vector mv2; };
Now we test memory allocation for 1 million test objects and measure time:
void testAllocHeap() { vector a(0,0,0); vector b(1,1,1); time_type startTime = local_time(); for(int i=0; i<1000000; i++) { TestObject *pointerToTestObject = new TestObject(a, b); delete pointerToTestObject; } time_type stopTime = local_time(); std::cout << "Time heap: " << stopTime-startTime <<"n"; } void testAllocStack() { vector a(0,0,0); vector b(1,1,1); time_type startTime = local_time(); for(int i=0; i<1000000; i++) { TestObject pointerToTestObject(a, b); } time_type stopTime = local_time(); std::cout << "Time stack: " << stopTime-startTime << "n"; }
Our measurements show that object creation as a const reference on stack is approximately 20 times more efficient then object allocation on heap.
Senior Software Engineer developing all kinds of stuff.
You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>
*
*
Be the first to comment.