Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer vs Variable speed in C++

At a job interview I was asked the question "In C++ how do you access a variable faster, though the normal variable identifier or though a pointer". I must say I did not have a good technical answer to the question so I took a wild guess.

I said that access time will probably be that same as normal variable/identifier is a pointer to the memory address where the value is stored, just like a pointer. In other words, that in terms of speed they both have the same performance, and that pointers are only different because we can specify the memory address we want them to point to.

The interviewer did not seem very convinced/satisfied with my answer (although he did not say anything, just carried on asking something else), therefore I though to come and ask SO'ers wether my answer was accurate, and if not why (from a theory and technical POV).

like image 908
Jerry Avatar asked Aug 02 '11 22:08

Jerry


People also ask

Are pointers faster than variables?

Faster and more efficient code can be written because pointers are closer to the hardware. That is, the compiler can more easily translate the operation into machine code. There is not as much overhead associated with pointers as might be present with other operators.

Does pointer increase execution speed?

Using a pointer does not increase execution speed.

Are pointers slow in C?

The (greatly oversimplified) answer is that, yes, pointers are slower. The longer answer is that it depends highly on what you're doing, specifically and the exact scenario.

Which is faster pointer or reference?

It's much faster and memory-efficient to copy a pointer than to copy many of the things a pointer is likely to point to. A reference is stored in as many bytes as required to hold an address on the computer. This often makes reference much smaller than the things they refer to.


2 Answers

When you access a "variable", you look up the address, and then fetch the value.

Remember - a pointer IS a variable. So actually, you:

a) look up the address (of the pointer variable),

b) fetch the value (the address stored at that variable)

... and then ...

c) fetch the value at the address pointed to.

So yes, accessing via "pointer" (rather than directly) DOES involve (a bit) of extra work and (slightly) longer time.

Exactly the same thing occurs whether or not it's a pointer variable (C or C++) or a reference variable (C++ only).

But the difference is enormously small.

like image 138
paulsm4 Avatar answered Sep 22 '22 06:09

paulsm4


A variable does not have to live in main memory. Depending on the circumstances, the compiler can store it in a register for all or part of its life, and accessing a register is much faster than accessing RAM.

like image 27
LaC Avatar answered Sep 19 '22 06:09

LaC