cpp_weekly icon indicating copy to clipboard operation
cpp_weekly copied to clipboard

How using `const` can dramatically improve code

Open lefticus opened this issue 2 years ago • 5 comments

https://compiler-explorer.com/z/8xfs6ee9q

lefticus avatar May 31 '23 21:05 lefticus

How does the Cpp2 equivalent of the Cpp1 inefficient way compares to the better Cpp1 version? See https://cpp2.godbolt.org/z/4bnG94TY4.

JohelEGP avatar May 31 '23 22:05 JohelEGP

https://compiler-explorer.com/z/8xfs6ee9q

I truly love C++ and I love how the language has been improving with the years. However this code is one of the best examples of why I think C++ should die.

fcolecumberri avatar Jun 01 '23 13:06 fcolecumberri

It's not exactly about using const or not for the temporary string, isn't it?... It's just that in the first version the string is initialized in two steps, first with the default constructor, then reassigned?

More variations: https://compiler-explorer.com/z/qTYezE5bs (which are all basically equivalent.)

Also more code is generated, but is the execution path longer? Looks like yes, it does benchmark slower than all the other variations that only assign it once (which are all the same run time): https://quick-bench.com/q/QmKEEn0RZj9jhpnh9BF2qP5TbPk

But why assign a temporary but only use it once? If you are going to use it for multiple calls after assigning it, or are going to modify or reassign it conditionally, then maybe the clarity of the code is worth the bit of technically wasted time in the initial construction etc.

reedhedges avatar Jun 26 '23 15:06 reedhedges

also this episode would need a note about how "const" might move something into the rodata section of the binary

lefticus avatar Sep 14 '23 14:09 lefticus

How does the Cpp2 equivalent of the Cpp1 inefficient way compares to the better Cpp1 version? See https://cpp2.godbolt.org/z/4bnG94TY4.

Here's the diff: https://godbolt.org/z/3K4dn4bqY. It seems to add quite a few more things.

JohelEGP avatar Sep 14 '23 14:09 JohelEGP