Archived

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

felonius

Const parameter passing and performance

Recommended Posts

Hi, I have been wondering lately whether I should be using const declarations on simple parameter types in C++. I.e. should I prefer int myfunction(const int x); over int myfunction(int x); Since simple arguments are passed by value, there are no semantic difference at all for the caller - so the only argument for using the top version should be performance. I am, however, not sure whether there are any performance difference between these two; I wouldn''t think so but one never knows.

Share this post


Link to post
Share on other sites
quote:
Original post by qwedcxza
If you want little performance you can use point as:

int myFunction( int *x );

that will incur additional dereference for each use of x, which will decrease performance.

for the original question: i don''t think it matters either.

---
Come to #directxdev IRC channel on AfterNET

Share this post


Link to post
Share on other sites
Concerning niyaws suggestion; that certainly is not faster. In fact it is slower.

I tried making a small benchmark and I can''t get any preformance difference either. So I think it probalby doesn''t matter.

Share this post


Link to post
Share on other sites
To summarize, there''s no point in qualifying "const" for
built-in types. They are always passed by copy anyway. And
passing a const-pointer or const-reference make is SLOWER
for the extra dereferencing.

For user-defined types, it''s definitely a good idea to pass
by const-reference if it''s larger than built-in types. In fact,
always pass by const-reference to avoid copying, unless there
is a specific reason you want to pass a copy (which is very rare).



Kami no Itte ga ore ni zettai naru!

Share this post


Link to post
Share on other sites
Please don''t do that. It doesn''t affect performance, but it is a pain in the ass. If I want to write a loop where I decrement x, e.g. while (x--) { do something; }, I can''t. I have to copy x or use a for loop.

In fact, since it doesn''t affect the caller, making a passed-by-value argument const actually exposes an implementation detail of the function, and therefore violates encapsulation.

Share this post


Link to post
Share on other sites