Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointers and execution speed

Tags:

c

pointers

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:

  • Dereferencing a single location requires two (or more) memory accesses (depending on number of indirection). Which will increase the execution time, compared to if it was used directly.

  • Passing a pointer to a large datatype to a function, like a structure can be beneficial, as only the address of the structure/union is getting copied and it's not getting passed by value. Therefore it should be faster in this case.

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.

like image 926
phoxis Avatar asked Dec 20 '12 07:12

phoxis


2 Answers

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.

like image 109
Mark Byers Avatar answered Sep 18 '22 04:09

Mark Byers


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.

like image 40
cxxl Avatar answered Sep 20 '22 04:09

cxxl