4

In a (C++) class I took recently the teacher mentioned that using the -> operator was a tiny bit slower than using dot notation and dereferencing your pointer manually (e.g. (*ptr)).

  1. Is this true, and, if so, why?
  2. Does this apply to C as well?
Marcus Hansson
  • 816
  • 2
  • 8
  • 17

1 Answers1

6

The -> operator is neither slower or faster than . operator. The fact is that dereferencing something is slower than just access to a memory location, because there is one more indirection. And this is a fact of life, either in C and C++ and any other language.

In C++, you have also references, so you can dereference something using the . too! So the problem here is not arrow-vs-dot, the problem is if the compiler can go straight to a value or if it must search for its address before.

Paolo M
  • 12,403
  • 6
  • 52
  • 73
  • `you have also references` yeah, but he definitely meant dereferencing a *pointer*, not "dereference a reference" (or whatever it's called). – Marcus Hansson Sep 24 '15 at 09:06
  • The OP (as I understood) was not talking about pointer vs. direct object access but different notations of accessing an object through a pointer, namely `p->member` vs. `(*p).member`, which are absolutely and categorically identical (in their default implementation). To Marcus: Get your money back. – Peter - Reinstate Monica Sep 24 '15 at 09:33
  • 1
    `Get your money back` I'm Swede. University's free. But if I'd payed for it, I would definitely demand my money back. – Marcus Hansson Sep 24 '15 at 09:43
  • @PeterSchneider Oh... I guess you're right! Well, then the answer would turn into a "**NO**" :) – Paolo M Sep 24 '15 at 09:48
  • That dereferencing something is slower " this is a fact of life, either in C and C++ and any other language." While that is correct, optimizing compilers -- most notably JIT compilers which have more information at hand -- can possibly optimize away the dereferencing if they can prove that the reference keeps pointing to the same object (which in C++ for example is always true for "references"). – Peter - Reinstate Monica Sep 24 '15 at 10:20
  • As an example, using a variable instead of a literal also involves an indirection, as I layed out elsewhere (cf. http://stackoverflow.com/a/32736116/3150802). When playing around with the code I saw that the compiler would translate `int i=11; int f(){ return i*i; }` into a simple "return 121" unless I excplicitly switched optimizing off. Comparable optimizations should happen with pointers. – Peter - Reinstate Monica Sep 24 '15 at 10:25