473,851 Members | 2,323 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

passing parameters by const& ... can it be overdone?

I have heard it is considered good practice to pass function parameters as
const& as often as possible, is this true? Is it possible to go overboard?
And if so why? Thanks a lot in advance everyone!

Christopher Diggins
http://www.cdiggins.com
Jul 22 '05
20 2153

"Method Man" <a@b.c> wrote in message
news:du******** ********@read1. cgocable.net...
Pass built-in types by value
and pass User Defined Types (UDTs) by const reference
and your code won't be far from optimal wherever you port it.


Again, you can not make general statements like that without knowing the
implementation details. Consider a device controller programmer who has
the
following UDT:

struct DISK_REGISTER {
unsigned ready:1;
unsigned error_occured:1 ;
unsigned disk_spinning:1 ;
unsigned write_protect:1 ;
unsigned head_loaded:1;
unsigned error_code:8;
unsigned track:9;
unsigned sector:5;
unsigned command:5;
};

For sake of argument, assume: sizeof(DISK_REG ISTER) == sizeof(int).

Now, say we needed to pass this struct into a function and modify all its
members. The extra level of indirection required by a const reference to
access the members would be much more inefficient than simply passing in
the
struct by value.


If I am not confused then this is not a good example because you simply
wouldn't be able to modify the members if you passed it by const reference.

Christopher Diggins
http://www.cdiggins.com
Jul 22 '05 #11
> I have heard it is considered good practice to pass function parameters as
const& as often as possible, is this true? Is it possible to go overboard?
And if so why? Thanks a lot in advance everyone!


Please read this:
1. Book "Effective C++" by Scott Meyers
Item 22: Prefer pass-by-reference to pass-by-value
http://www.ncpod.org:16080/shared/Ef...EC/EI22_FR.HTM

2. Free electronic book "Thinking in C++" by Bruce Eckel
References in C++
http://www.savinov.spb.ru/think/tic0120.html#Heading311
Jul 22 '05 #12
"Markus Elfring" <Ma************ @web.de> wrote in message
news:40******** *************** ***@posting.goo gle.com...
I have heard it is considered good practice to pass function parameters
as
const& as often as possible, is this true? Is it possible to go
overboard?
And if so why? Thanks a lot in advance everyone!


Please read this:
1. Book "Effective C++" by Scott Meyers
Item 22: Prefer pass-by-reference to pass-by-value
http://www.ncpod.org:16080/shared/Ef...EC/EI22_FR.HTM

2. Free electronic book "Thinking in C++" by Bruce Eckel
References in C++
http://www.savinov.spb.ru/think/tic0120.html#Heading311


Thank you for the links.

Christopher Diggins
http://www.heron-language.com
Jul 22 '05 #13

"christophe r diggins" <cd******@video tron.ca> wrote in message
news:9z******** **********@webe r.videotron.net ...

"Method Man" <a@b.c> wrote in message
news:du******** ********@read1. cgocable.net...
Pass built-in types by value
and pass User Defined Types (UDTs) by const reference
and your code won't be far from optimal wherever you port it.
Again, you can not make general statements like that without knowing the
implementation details. Consider a device controller programmer who has
the
following UDT:

struct DISK_REGISTER {
unsigned ready:1;
unsigned error_occured:1 ;
unsigned disk_spinning:1 ;
unsigned write_protect:1 ;
unsigned head_loaded:1;
unsigned error_code:8;
unsigned track:9;
unsigned sector:5;
unsigned command:5;
};

For sake of argument, assume: sizeof(DISK_REG ISTER) == sizeof(int).

Now, say we needed to pass this struct into a function and modify all its members. The extra level of indirection required by a const reference to
access the members would be much more inefficient than simply passing in
the
struct by value.


If I am not confused then this is not a good example because you simply
wouldn't be able to modify the members if you passed it by const

reference.


Sorry, I should not have said "modified", but simply "accessed".
Jul 22 '05 #14
Method Man wrote:
Pass built-in types by value
and pass User Defined Types (UDTs) by const reference
and your code won't be far from optimal wherever you port it.

Again, you can not make general statements like that without knowing the
implementation details. Consider a device controller programmer who has the
following UDT:

struct DISK_REGISTER {
unsigned ready:1;
unsigned error_occured:1 ;
unsigned disk_spinning:1 ;
unsigned write_protect:1 ;
unsigned head_loaded:1;
unsigned error_code:8;
unsigned track:9;
unsigned sector:5;
unsigned command:5;
};

For sake of argument, assume: sizeof(DISK_REG ISTER) == sizeof(int).

Now, say we needed to pass this struct into a function and modify all its
members. The extra level of indirection required by a const reference to
access the members would be much more inefficient than simply passing in the
struct by value.


Please construct a pair of benchmark programs:
one that passes a DISK_REGISTER by const reference and
another that passes a DISK_REGISTER by value.
Show us that you can measure a significant difference
in the time required to execute each program.
Jul 22 '05 #15
"christophe r diggins" <cd******@video tron.ca> wrote in message news:<3k******* **************@ weber.videotron .net>...
I have heard it is considered good practice to pass function parameters as
const& as often as possible, is this true? Is it possible to go overboard?
And if so why? Thanks a lot in advance everyone!

Christopher Diggins
http://www.cdiggins.com


Functors are to be designed to be passed by value.

See Effective STL.

d
Jul 22 '05 #16
In message <4d************ **************@ posting.google. com>, Andre Dajd
<an********@hot mail.com> writes
"christophe r diggins" <cd******@video tron.ca> wrote in message
news:<3k****** *************** @weber.videotro n.net>...
I have heard it is considered good practice to pass function parameters as
const& as often as possible, is this true? Is it possible to go overboard?
And if so why? Thanks a lot in advance everyone!

Functors are to be designed to be passed by value.

That's a requirement imposed on the *functor*, not the function to which
it's passed, and it's not there to address this particular question.

Forbidding functors to have mutable internal state (which is effectively
what it does) allows the library implementor more freedom in designing
algorithms which can use multiple copies of the functor if they need to.

--
Richard Herring
Jul 22 '05 #17
"E. Robert Tisdale" <E.************ **@jpl.nasa.gov > wrote in message news:<cn******* ***@nntp1.jpl.n asa.gov>...

Please construct a pair of benchmark programs:
one that passes a DISK_REGISTER by const reference and
another that passes a DISK_REGISTER by value.
Show us that you can measure a significant difference
in the time required to execute each program.


The simplest benchmark program.

#include <iostream>
#include <string>

struct DISK_REGISTER {
unsigned ready:1;
unsigned error_occured:1 ;
unsigned disk_spinning:1 ;
unsigned write_protect:1 ;
unsigned head_loaded:1;
unsigned error_code:8;
unsigned track:9;
unsigned sector:5;
unsigned command:5;
};

void f(const DISK_REGISTER &r) {
(void) r;
}

void g(DISK_REGISTER r) {
(void) r;
}

int
main(int argc, char **argv)
{
if (argc > 1) {
const std::string arg = argv[1];
DISK_REGISTER r;
if (arg == "f") for (unsigned i = 0; i < 1000000000; i++) f(r);
else if (arg == "g") for (unsigned i = 0; i < 1000000000; i++) g(r);
else std::cerr << argv[0] << ": <f|g>" << std::endl; return 1;
}
return 0;
}

4 second difference in favor of pass by value for 1 billion iterations.
Compiled with gcc 3.3.4 without optimizations (run on 400Mhz box in case
you wonder why it took so long)

pkrumins$ time ./test g

real 0m27.953s
user 0m27.370s
sys 0m0.100s

pkrumins$ time ./test f

real 0m31.652s
user 0m31.060s
sys 0m0.130s
P.Krumins
Jul 22 '05 #18
Peteris Krumins wrote:
E. Robert Tisdale wrote:
Please construct a pair of benchmark programs:
one that passes a DISK_REGISTER by const reference and
another that passes a DISK_REGISTER by value.
Show us that you can measure a significant difference
in the time required to execute each program.

The simplest benchmark program.

#include <iostream>
#include <string>

struct DISK_REGISTER {
unsigned ready:1;
unsigned error_occured:1 ;
unsigned disk_spinning:1 ;
unsigned write_protect:1 ;
unsigned head_loaded:1;
unsigned error_code:8;
unsigned track:9;
unsigned sector:5;
unsigned command:5;
};

void f(const DISK_REGISTER &r) {
(void) r;
}

void g(DISK_REGISTER r) {
(void) r;
}

int
main(int argc, char **argv)
{
if (argc > 1) {
const std::string arg = argv[1];
DISK_REGISTER r;
if (arg == "f") for (unsigned i = 0; i < 1000000000; i++) f(r);
else if (arg == "g") for (unsigned i = 0; i < 1000000000; i++) g(r);
else std::cerr << argv[0] << ": <f|g>" << std::endl; return 1;
}
return 0;
}

4 second difference in favor of pass by value for 1 billion iterations.
Compiled with gcc 3.3.4 without optimizations (run on 400Mhz box in case
you wonder why it took so long)

pkrumins$ time ./test g

real 0m27.953s
user 0m27.370s
sys 0m0.100s

pkrumins$ time ./test f

real 0m31.652s
user 0m31.060s
sys 0m0.130s


That's a good start.

First,
convince us that your compiler did *not* simply inline
f(const DISK_REGISTER&) and/or g(DISK_REGISTER ).
Show us the compiler version and options that you used.

Second,
convince us that your results are *significant*.
Run each case several times
and calculate the average time and standard deviation.
The difference in average times must be at least as large
as the standard deviation(s).
Jul 22 '05 #19
"E. Robert Tisdale" <E.************ **@jpl.nasa.gov > wrote in message news:<cn******* ***@nntp1.jpl.n asa.gov>...
That's a good start.

First,
convince us that your compiler did *not* simply inline
f(const DISK_REGISTER&) and/or g(DISK_REGISTER ).
Show us the compiler version and options that you used.

pkrumins$ g++ test.cpp -o test -W -Wall
pkrumins$ g++ -v
gcc version 3.3.4

Since I am was optimizing, no functions were inlined.
Second,
convince us that your results are *significant*.
Run each case several times
and calculate the average time and standard deviation.
The difference in average times must be at least as large
as the standard deviation(s).


I changed the number of iterations for each test to 200 million, so
the tests took less time.
I did 10 observations.

Here are the results (sorted by time):

1. f(const DISK_REGISTER&)

N time (s) delta time (s) (delta time)^2 (s^2)
1 6,324 0,0195 0,00038025
2 6,326 0,0175 0,00030625
3 6,327 0,0165 0,00027225
4 6,334 0,0095 0,00009025
5 6,336 0,0075 0,00005625
6 6,350 0,0065 0,00004225
7 6,353 0,0095 0,00009025
8 6,354 0,0105 0,00011025
9 6,363 0,0195 0,00038025
10 6,368 0,0245 0,00060025
----- ----------
avg: 6,3435 sum: 0,00232850

standard deviation:
sqrt(sum / (n - 1)) = 0,016084844 (s)

2. g(DISK_REGISTER )
N time (s) delta time (s) (delta time)^2 (s^2)
1 5,596 0,0048 0,00002304
2 5,597 0,0038 0,00001444
3 5,599 0,0018 0,00000324
4 5,599 0,0018 0,00000324
5 5,600 0,0008 0,00000064
6 5,600 0,0008 0,00000064
7 5,601 0,0002 0,00000004
8 5,603 0,0022 0,00000484
9 5,604 0,0032 0,00001024
10 5,609 0,0082 0,00006724
----- ----------
avg: 5,601 sum: 0,00012760

standard deviation: 0,003765339 (s)
Now the results are significant and we see that pass by value is
faster than pass by const reference.
P.Krumins
Jul 22 '05 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

25
2958
by: Victor Bazarov | last post by:
In the project I'm maintaining I've seen two distinct techniques used for returning an object from a function. One is AType function(AType const& arg) { AType retval(arg); // or default construction and then.. // some other processing and/or changing 'retval' return retval; }
0
9895
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9744
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10725
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10352
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9503
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7900
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7072
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5931
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4547
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.