Const parameter passing and performance

Started by
4 comments, last by felonius 21 years, 8 months ago
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.
Jacob Marner, M.Sc.Console Programmer, Deadline Games
Advertisement

I think the purpose of const var is avoid you modify this var in you function. If you want little performance you can use point as:

int myFunction( int *x );
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
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.
Jacob Marner, M.Sc.Console Programmer, Deadline Games
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!
神はサイコロを振らない!
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.

This topic is closed to new replies.

Advertisement