r/cpp • • May 25 '21

[Belay the C++] Lambdas as const ref

https://belaycpp.com/2021/05/25/lambdas-as-const-ref/
14 Upvotes

27 comments sorted by

24

u/witcher_rat May 25 '21

The const ref of the lambda having better performance than a value of the lambda seems weird.

So I went on the benchmark site and found that if you run it multiple times, the numbers change each time. Sometimes both methods have the same perf, sometimes one beats out the other.

So I think the article's wrong.

Also, for that type of lambda in the article's example I normally just make it static const (no ref).

For example: quick-bench.

7

u/kalmoc May 25 '21

As I wrote in another comment: The bencharmk is most likely worthless, as the compiler will almost certainly optimize the count_if away completely on O2 and O3 without a benchmark::DoNotOptimize

-3

u/Vultrao May 25 '21

Well, I'd like to see your result, because for the sake of the article (and this response) I cleared the cache and re-ran some examples multiple times, and each time I had the same ratio.

The numbers themselves don't mean anything, as I state in the article, because of the lack of unit.

For your comment about staic, well it is true, but a bit off-topic.

2

u/witcher_rat May 25 '21

Sure, here you go: https://imgur.com/a/3wGLsPK

As you can see, those show the equal results. They also show some cases where the results are completely bogus. I'm not sure how the benchmark site works, but it appears to be a bit unstable. (not that I'm complaining - it's free after all)

8

u/dodheim May 25 '21

I assume the code is just being optimized away entirely due to the lack of outputs and/or benchmark::DoNotOptimize calls.

6

u/blipman17 May 25 '21

Yep, since the result of std::count_if is thrown away and all other values being constant, the compiler can simply remove them and no observeable side-effect has changed according to the c++ spec. Therefore, the compiler will most likely inline all constants and (lambda) functions, realize they don't do anything and not emit code for inside the loop. This means this benchmark is most likely testing the speed of a loop.

3

u/TheSuperWig May 25 '21

There's a godbolt link and it shows they all do nothing.

12

u/kalmoc May 25 '21

I think there is a pretty high chance that compiler just completely optimized the code away on O2 and O3 and even if it didn't / if you fixed that, I wouldn't put any weight behind a one digit (or less) difference on quickbench.

10

u/n1ghtyunso May 25 '21

Comparing the assembly would probably be the correct thing to do. Chances are its the same

3

u/kalmoc May 25 '21

Yes, that would be my assumption too.

-7

u/Vultrao May 25 '21

The assembly shown in the article has no optimization option : https://godbolt.org/z/va5nG33cK

9

u/kalmoc May 25 '21

that assembly has nothing to do with the benchmarks, which have been done with O0 - O3

34

u/witcher_rat May 25 '21

I'm confused by his being surprised about a const ref binding to an rvalue.

Of course a const ref binds to an rvalue and keeps it alive. All kinds of code would break horribly if this weren't the case.

He goes on to say:

This is a very simple fact that is really clear in the standard, but it is rarely used in code and referenced on the web.

The reason for that is that binding to a const ref instead of a const value – or even a plain value – seems useless.

Ummm, what?!?

All manner of code out there generically/blindly invoke functions and hold their return value using a const ref, and thus don't have to care whether the function they invoked returned a value or reference. (so long as they only hold it within a function scope, etc., etc.)

Am I missing something?

7

u/dodheim May 25 '21

0

u/Vultrao May 25 '21

Nice, I didn't find this article while doing my researches. Thanks !

13

u/syyyr May 25 '21

Also, temporaries bind to const ref function arguments

6

u/witcher_rat May 25 '21

Yeah, I was actually going to mention that as the main example... but I didn't want to cloud the issue since as far as I know the lifetime of anything passed to a function is as long as the expression invoking it. (it just so happens that a non-const lvalue won't bind to an rvalue, which is what prevents it from compiling)

By that I mean even this will work fine:

// some function taking a string_view
void func(std::string_view s);

// invoking above function with a temp string
func(std::string("hello"));

...even though no const ref is in sight whatsoever.

But obviously this won't compile:

// some function taking a non-const ref
void func(std::string& s);

// fails to compile
func(std::string("hello"));

because the non-const lvalue won't bind to an rvalue, for obvious good reasons... even though technically in this use-case it would be fine, afaik.

2

u/evaned May 27 '21

Of course a const ref binds to an rvalue and keeps it alive.

FWIW, I don't think the lifetime extension part of that deserves an 'of course' -- I was surprised by that when I first saw it.

2

u/witcher_rat May 27 '21

Yeah you're right - "of course" is a too strong. I guess I meant it more in that it's been that way since what, C++11? That's a decade ago. (Though to be fair I know many people are still stuck on pre-11 codebases.)

I can barely remember what the C++98/03 rules even were at this point. :)

1

u/dodheim May 27 '21

Since C++98. The language had that even before it had value-initialization.

1

u/witcher_rat May 27 '21

Yeah I thought so too, but I checked cppreference and it says C++11 for it, though that could easily be wrong or I could be reading it wrong. (I'm saddened I can no longer remember these things, as I started in C++ in the late 80's and yet have no real recollection of the rules back then either)

1

u/dodheim May 27 '21

The latter, I guess. ;-D   C++11 is only mentioned to say that rvalue refs to temporaries do lifetime extension as well.

1

u/MakersF May 26 '21

I remember reading an article explaining why a comet l-value binding to an r-value is conceptually wrong, but it has been specified like that to be compatible with all the code written before c++11.

The argument was that "const &&" is the cv-ref with the least requirements (cannot modify it, and accepts temporaries), so when a function just needs a "view" on something, should accept a "const &&", not a "const &&". The standard should have specified that "[const] &" could bind to "const &&". But this, while logically sound, would have made r-value refs break a lot of code. So they went with the rules we have. It was a good article, it's interesting to see how features we give for granted would be different if we reasoned from first principles. Ufortunately I don't have the link anymore

1

u/NilacTheGrim Jun 03 '21

Am I missing something?

No, you are not. You're right on the money.

In generic code (or even in some non-generic code where the API may change) -- it's a very good idea to bind to const ref for precisely the reason you mentioned -- avoid an unneeded copy in the case where the return type is const T & someFunc() but you are declaring the receiver of the return value as: const T myt = someFunc(); // this will create an extra copy when perhaps you don't need one

23

u/staletic reddit thinks /u/_bstaletic is a bot May 25 '21

I’ll use Quick C++ Benchmarks (quick-bench.com) to evaluate execution time.

You've even shown that the assembly is exactly the same. Why would you expect any difference in performance, if the code gen is identical? The difference you've measured is just noise.

Even across architectures (x86, ARM, AArch64) and compilers (gcc, clang), the codegen diff is nowhere to be found.

Also, online services aren't a reliable way to benchmark anything, as you have no control over the load the remote server's CPU is under.

2

u/goranlepuz May 25 '21

This language is smart, I tend to forget it, but it is only logical that if you try to bind a cons ref to a temporary object, the object will be put on the memory stack and accessed via the const ref.

There is a Sutter discussion of that, somebody linked it here, it is +/- common knowledge since year 2000 when Alexandrescu the first ScopeGuard in Dr Dobbs.

But! I am writing this just to say: I don't see a reason why this is "logical". What magic fairy dust makes a const ref live longer, but no const doesn't? What possible reasoning can there be to mix const and reference lifetime? Why not make it possible to return that const ref out of the function and make it live even longer? (I know why, but stack-schmack...)

1

u/Rude-Significance-50 May 25 '21

I wouldn't expect any difference, no. Whatever happens, the object has to be built somewhere. It might use RVO, it might be moved...it might be copied. No matter what, it's got to be formed. Is your VARIABLE going to be a reference to or be direct, this object is still there somewhere.

When the return is a reference of course it can pay to also use reference to avoid any sort of copy or anything...and the fact that this code could still work if it later creates a value is...of dubious quality.