Archived

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

Exellion

Reference to small types = superfluous?

Recommended Posts

By passing references to functions instead of a copy of the data we only send a memory address (4 bytes), right? The use of this is very clear when handling large structures but what about when I pass an int or a char? These types are so small that the same amount of data would be sent in either case (reference or not reference). So, to the real question: Is it still better to pass an int as a reference because of the copying that occurs otherwise?

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
It''s better to pass int by value because then it can be directly accessed. By sending it as a referece, it only sends it''s address, and the value has to be looked up every time you use the reference.. Passing 8 byte structures by value can also be faster than passing them by value, due to the indirect access with references.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
> Passing 8 byte structures by value can also be faster than passing them by value

You know what I meant to say..

Share this post


Link to post
Share on other sites
Depends on what you''re gonna do with the integer. If you pass it to a function that (for example) doubles it, it would be better to pass it with a pointer or referance and alter the memory inside the function instead of first making a copy of the value, double the copy and return it by the return value of the function.

Anyway, there can''t be _too_ much of a speed difference whether you copy the integer or not; just keep it simple as possible is my advice.

-Lord Maz-

Share this post


Link to post
Share on other sites
That''s the only problem with a reference - so easy to forget it''s actually a pointer in disguise. Though that''s also it''s advantage for ease of use! Persoanlly I prefer pointers to references as it''s closer to the machine code - references are an abstraction sort of wheras pointers have a direct ASM equaivalent. Just my 2c!

Share this post


Link to post
Share on other sites
You should apply this simple rule :

If you''re passing an object/structure :
- Pass it by const reference if it is a read only argument
- Pass it by reference if it is a read/write argument

If you''re passing a standard type variable :
- Pass it by value if it is a read only argument
- Pass it as a reference if it is a read/write argument

> Is it still better to pass an int as a reference because of the
> copying that occurs otherwise?

If you pass it by reference, you still have to push its address on the stack (as you would with its value).

Share this post


Link to post
Share on other sites