phoxis
phoxis

Reputation: 61910

Pointers and execution speed

Some blogs and sites were talking about pointers are beneficial one of the causes was because the "execution speed" will be better in a program with pointers than without pointers. The thing I can work out is that:

For example just by force introducing pointers without any need as:

int a, b, *p, *q, c, *d;
p = &a;
q = &b;
d = &c

// get values in a, b 

*d = *p + *q;  // why the heck this would be faster
c = a + b;     // than this code? 

I checked the assembler output using gcc -S -masm=intel file.c The pointer version has a lot of loading memory and storing for the dereferences than the direct method.

Am I missing something?

Note: The question is not related to just the code. The code is just an example. Not considering compiler optimizations.

Upvotes: 6

Views: 1899

Answers (4)

Bok McDonagh
Bok McDonagh

Reputation: 1447

You are right in your example - that code would run slower. One place where it can be faster is when making a function call:

void foo( Object Obj );
void bar( const Object * pObj );

void main()
{
    Object theObject;
    foo( theObject );  //  Creates a copy of theObject which is then used in the function.
    bar( &theObject );  //  Creates a copy of the memory address only, then  the function references the original object within.
}

bar is faster as we don't need to copy the entire object (assuming the object is more than just a base data type). Most people would use a reference rather than a pointer in this instance, however.

void foobar( const Object & Obj );

Upvotes: 1

coder005
coder005

Reputation: 79

Mark Byers is absolutely right. You cannot judge the power of pointers in such simple program.They are used to optimize the memory management and faster execution of programs where there are excessive use of data structures and references are done through addresses. Consider when you start a program it takes some time in loading but with efficient use of pointers and skills if the program loads even 1 second earlier that's a large accomplishment.

Upvotes: 0

cxxl
cxxl

Reputation: 5379

As you pointed out: Passing a pointer to a large datatype to a function; here the structure is an int, so it's hardly large. BTW: I guess gcc will optimize away the pointer accesses when you use -O2.

Apart from that your understanding is correct.

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 837996

I think your conclusions are basically right. The author did not mean that using more pointers will always speed up all code. That's obviously nonsense.

But there are times when it is faster to pass a pointer to data instead of copying that data.

Upvotes: 6

Related Questions