I’m wondering whether sometimes (depends on the platform or compiler or context in code etc) a reference can be more efficient than a pointer?
I’m wondering whether sometimes (depends on the platform or compiler or context in code
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes, it may. The only way we could say “it can’t” is if there were a requirement (explicit or implied) in the standard that references be as slow or slower than equivalent pointers in all cases. There is no such requirement, since the standard doesn’t concern itself with that kind of performance detail.
For example, at low optimization levels it would be reasonable for this:
to be a little slower than this:
simply because it’s a little easier in the first case for the compiler to detect that it can avoid the indirection entirely –
nris explicitly an alias forneverywhere it is in scope, whereas*npjust so happens to remain an alias fornbecause we never assign tonpafter it is initialized. The result with low optimization might well be more indirection in the pointer case and a less efficient loop.Take a look at the code your compiler emits, though – gcc with no optimization emits the same code for me, it looks to have spotted the alias in both cases and is using a register for the total and a stack slot for
i.Of course you’d expect a good optimizing compiler to “understand” the aliasing in both cases, and emit code that stores
nin a register, and only touches that register (not memory) in the loop.