memory

i was just wondering, which program is best if were looking at mamory

in first version of program, sign is created only once, and in second ver. its created each new loop cycle

so, are (speaking of memory) both programs equivalent to each other or not?

ver1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

using namespace std;

int main()
{
	char sign;

	for( int i=33; i < 256; ++i)
	{
		sign = i;

		cout << i <<  ": " << sign << " ";

		if( (i % 8) == 0)
		{
			cout << endl;
		}
	}
}



ver2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

using namespace std;

int main()
{

	for( int i=33; i < 256; ++i)
	{
		char sign = i;

		cout << i <<  ": " << sign << " ";

		if( (i % 8) == 0)
		{
			cout << endl;
		}
	}
}
This is something I've always been curious about. Is the variable pushed only once when the loop starts and then popped when it breaks, or pushed and popped after every iteration?
Since it would have a performance penalty, I'll do a little benchmark:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <ctime>

#define N 1000000000

int main(){
	unsigned t0,t1;
	t0=clock();
	for (unsigned a=0;a<N;a++){
		unsigned b=a;
		b++; //Added just in case the optimizer decided an empty loop was better
	}
	t1=clock();
	std::cout <<"time for inner declaration: "<<t1-t0<<" ms"<<std::endl;
	t0=clock();
	unsigned b;
	for (unsigned a=0;a<N;a++){
		b=a;
		b++;
	}
	t1=clock();
	std::cout <<"time for outer declaration: "<<t1-t0<<" ms"<<std::endl;
	return 0;
}

Output for unoptimized:
time for inner declaration: 5953 ms
time for outer declaration: 5937 ms

Output for optimized:
time for inner declaration: 547 ms
time for outer declaration: 547 ms


Outer declaration is 0.27% faster than inner declaration.
Conclusion: There is no penalty.
With a good optimizing compiler, the loops should be equivalent, in that the stack space is allocated only once, as opposed to once each iteration.

This does not apply to non-POD types with non-trivial constructors/destructors, however, as in those cases, the constructor and destructor will be called each iteration.

Topic archived. No new replies allowed.