nowi
nowi

Reputation: 487

Cheap pass by value vs pass by constant reference

Specifically with regard to MSVC on VS 2019, what does const & on cheap objects look like with maximum optimization? Can one say for certain that it is always at least not detrimental to do things by const &?

void foo( char );
void foo( const char & );

I know it's implementation defined as to whether or not a reference is a pointer but I just want to know specifically for MSVC's implementation if it is actually bad to have const & everywhere.

If so, should I specialize heavily used template functions to pass by value instead of reference for primitives with size < ptr?

Upvotes: 0

Views: 68

Answers (1)

John Zwinck
John Zwinck

Reputation: 249193

If so, should I specialize heavily used template functions to pass by value instead of reference for primitives with size < ptr?

In general, no. Template functions almost always have their entire definition visible where called, which means if your optimizing compiler (of which MSVC is a very good one) sees an opportunity, it will not be thwarted by which way you chose.

Of course there are exceptions to every rule, including templates whose definitions are not visible (and e.g. use explicit instantiation), and when calling a function via function pointer rather than by name.

99.5% of the time, you should not worry about this at all. If you want to spend time on performance, spend it on profiling.

Upvotes: 2

Related Questions