Question

I have to pass a lot of pointers in my code in the midst of a big loop, (so I have lots of expressions like foo(&x, &y, ...)). I was wondering whether I should store the pointers as separate variables (i.e. cache) for performance (at the cost of introducing more variables and clutter in my code)?

(Doing lots of matrix mult. and the CUBLAS library insists on pointers...)

Was it helpful?

Solution

No -- the address-of operator is about as inexpensive/fast as anything you can hope for. It's possible to overload it, and such an overload could be slower, but overloading it at all is fairly unusual.

OTHER TIPS

std::addressof incurs no penalty at all. When it boils down to assembly code, we only refer to objects through their addresses anyway so the information is already at hand.

Concerning operator&, it depends whether it has been overloaded or not. The original, non-overloaded version behaves exactly like std::addressof. However if operator& has been overloaded (which is a very bad idea anyway, and quite frowned upon), all bets are off since we can't guess what the overloaded implementation will be.

So the answer to your question is: no need to store the pointers separately, you can just use std::addressof or operator& whenever you need them, even if you have to repeat it.

in C++ there are references, what you are describing sounds more like a behaviour for the C language rather than C++.

that kind of signature for C++ methods it's usually implemented to avoid copying, by default when you call a method and pass some arguments to it, this arguments generate a local copy, having references it's a technique that help you avoid this overhead for the copy.

It would be very efficient. If you are using Linux, you can check by using objdump. The following is how fooP(&var1, &var2) looks like in the x86 architecture. It is nothing more than a LEA instruction.

 fooP(&var1, &var2);
 8048642:       8d 44 24 1c        lea    0x1c(%esp),%eax  -> this is to get the address of var2 to eax
 8048646:       89 44 24 04        mov    %eax,0x4(%esp)   -> this is to save the address to the stack for later fooP call
 804864a:       8d 44 24 18        lea    0x18(%esp),%eax  -> address of var1
 804864e:       89 04 24           mov    %eax,(%esp)
 8048651:       e8 be ff ff ff     call   8048614 <_Z4fooPPiS_>

Reference in this case is actually same as the above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top