Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are references or pointers faster?

From what I know, references are just another name for a variable whilst pointers are their own variable. Pointers take up space. People often say "use a reference or pointer" but they don't say which is better. If references take up no memory of their own, then references win in that department. What I don't know is if the compiler makes a distinction between references and normal variable. If you do operations on a reference, does it compile to the same code as normal variable?

like image 906
user4298783 Avatar asked Nov 27 '14 06:11

user4298783


People also ask

Is it better to use pointer or reference?

References are usually preferred over pointers whenever you don't need “reseating”. This usually means that references are most useful in a class's public interface. References typically appear on the skin of an object, and pointers on the inside.

Do pointers work faster?

Pointers save memory space. Execution time with pointers is faster because data are manipulated with the address, that is, direct access to memory location. Memory is accessed efficiently with the pointers.

Is it faster to pass by value or reference?

As a rule of thumb, passing by reference or pointer is typically faster than passing by value, if the amount of data passed by value is larger than the size of a pointer.

Are pointers faster than variables?

If you have a pointer (or a reference) to data, then you have two levels of memory access. First to load an address from the pointer (or reference) and then second to actually load the data. If you simply directly reference a variable, there is only one level of memory access. So here, a variable is faster.


1 Answers

Internally references are also implemented in terms of pointer. So, it's difficult to say which is faster pointer/reference.

It's a usage of these two which makes a difference.

For example you want to pass by reference a parameter to the function.

void func(int& a)    case_1
{
  //No need to check for NULL reference...
}
void func(int* a)    case_2
{
  //Need o check if pointer is not NULL
}

In case_2 you have to explicitly check if pointer is not NULL before dereferncing it whereas that's not the case with references because references are initialized to something.

Assumption is that you are playing game in civilized manner i.e

You are not doing something like:-

int*p = NULL;
int &a = *p;
like image 128
ravi Avatar answered Sep 21 '22 07:09

ravi