Archived

This topic is now archived and is closed to further replies.

robert_s

Passing by REFERENCE or by POINTER - which one is FASTER?

Recommended Posts

Hi I am not sure whether passing by pointer is faster than by reference. Which one needs less CPU processing and is faster? Below I''ll show an example of two cases which seem to be doing the same thing: Case 1: void func( int &height ) { height += 20; // value modified } Case 2 : void func( int *height ) { *height += 20; // value modified } In both cases the value height can be modified. These seem to me identical. Another example. Similar but they are constants: Case 3: void func( const int &height ) { height += 20; // Error: cant modify } Case 4 : void func( const int *height ) { *height += 20; // Error: cant modify } Again the same thing. Now. Please tell me which method is faster and what is really different here. I know that pointers can be used to pass arrays but lets forget about arrays now. I am passing only a single value. All I know that both cases are faster than pass-by-value. Reference holds the address of the variable that is stored in memory and pointer points at that address and must be dereferenced to extract a value of the address it is pointing to. So, what is the difference here and which one is a better practice to use *Performance*. Case 1,2 (References) or Case 2,4 (Pointers)?

Share this post


Link to post
Share on other sites
Actually, in both cases passing by value is faster than either. An integer is (at least in MSVC++) 4 bytes, as is a pointer and a reference, so there's no difference there. With a pointer, you have to access memory once to get the address of the variable, and then again to access the variable itself.

Of course, the results you want can't be achieved with passing by value, but this is just a heads up.

As for speed difference between pointers and references, I am not aware of any, and it would be negligible in any case.

Basically, if you're concerned about these things, you're wasting your time.

[edited by - twix on July 3, 2003 1:01:14 PM]

Share this post


Link to post
Share on other sites
There is no performance difference between a pointer and a reference. The only difference is that the compiler does all of the dereferencing for you. In other words, when you say "yada = value;", the compiler effectively replaces that with "*yada = value;".

Neither is "better" practice. It''s really what you prefer.

Share this post


Link to post
Share on other sites