I have a structure in which there are three float variables, and in a bigger program, I'm using an array of these structure objects. Now, I thought that each time in a loop when I was using values of these structures, I was creating a new copy of those objects by assigning:
like
struct A copy1 = original;
So I thought, to improve performance, why not create a const reference of this variable, because I just want to use the values, not modify them.
But when I made a test program to compare their efficiences, I did not get much difference - and strangely, the const reference one gave lower performance.. Can you tell me why?
Here's the code i tested with:
// Hello2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
#include<queue>
#include<stack>
#include<windows.h>
#include<winbase.h>
using namespace std;
#define K_LIMIT 10
struct A
{
float c,d,e;
};
int main(int argc, char *argv[])
{
LARGE_INTEGER start,end, start2, end2, start3, end3;
unsigned long i,j,k;
LARGE_INTEGER startTime; // For converting tick into real time
LARGE_INTEGER finishTime;
LARGE_INTEGER ticksPerSecond;
// get the high resolution counter's accuracy
QueryPerformanceFrequency(&ticksPerSecond);
/*******/
A something;
something.c=534.234;
something.d=234.234;
something.e=241.32;
QueryPerformanceCounter(&start);
for(i=0;i<10000;i++) for(j=0;j<10000;j++) for(k=0;k<K_LIMIT;k++)
{
A other = something;
}
QueryPerformanceCounter(&end);
//cout<<endl<<start<<endl<<end<<endl;
cout<<"Time elapsed in first= "<<(end.QuadPart-start.QuadPart)/(float) ticksPerSecond.QuadPart<<endl;
QueryPerformanceCounter(&start2);
for(i=0;i<10000;i++) for(j=0;j<10000;j++) for(k=0;k<K_LIMIT;k++)
{
const A& other2=something;
}
QueryPerformanceCounter(&end2);
//cout<<endl<<start2<<endl<<end2<<endl;
cout<<"Time elapsed in second= "<<(end2.QuadPart-start2.QuadPart)/(float) ticksPerSecond.QuadPart<<endl;
getchar();
}