Optimizing operator[]

Hi, i create smart pointers class. When i start to test it, i was upset. Because when i calculate the time to execution of func1, it was 5 times slower than func2.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void func1()
{
	SmartPtr<int> p(300000000); //creates array of 300000000 ints
	for(int i = 0; i < 300000000; i++)
		p[i] = i; //here is called operator[]
}

void func2()
{
	int * k = new int[300000000];
	for(int i = 0; i < 300000000; i++)
		k[i] = i;
	delete[] k;
}


interesting thing is that, when i delete
p[i] = i; this part of code func1 and func2 time is equal.
So i think, there is some problem in operator[]
here is it's code
1
2
3
4
		T& operator[](ptrdiff_t ind)
		{
			return pointer[ind];
		}

what i'm doing wrong?
Have you inlined your operator[]? If you haven't, you'd expect it to show up as slower in a 300Million iteration loop.
Maybe your operator[] isn't inline?
operator[] is declared in body of class, so it is automatically inlined.
Have any other ideas?
Do what the other two said regardless of what you think and try again :)

If that doesnt work you could post the rest of the SmartPtr class

Also, do you know where it is so slow? At the declaration of SmartPtr p or in the loop...?
Last edited on
Skillless, please read your post, it the worst post i ever saw.
Also, do you know where it is so slow? At the declaration of SmartPtr p or in the loop...?

next time when you're posting, please read the first post!
problem solved, the solution was very interesting.
thanks for your replies.
it the worst post i ever saw.

That's kind of rude.

the solution was very interesting.

What was it?
Alright alright

Explain to me what inline means then, akmal, because i seem to have missed the point, i never knew that if a function is in the body of a class it becomes an inline function.
And, what was the solution?
Last edited on
You're compiling with -O3, right?
Skillless, excuse me).
I was testing in debug mode, when i start testing in release mode it was good, because time of my smart pointers and c++ pointers is equal).
I think in debug mode there is a lot of debug info, am i right?
I'm using VS2008 compiler.
I think in debug mode there is a lot of debug info, am i right?


Debug mode generally doesn't inline functions because it makes it harder/impossible to support breakpoints.
Skillless wrote:
i never knew that if a function is in the body of a class it becomes an inline function.

http://cplusplus.com/forum/articles/10627/#msg49884
Topic archived. No new replies allowed.