Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How using const can dramatically improve code #297

Open
lefticus opened this issue May 31, 2023 · 5 comments
Open

How using const can dramatically improve code #297

lefticus opened this issue May 31, 2023 · 5 comments

Comments

@lefticus
Copy link
Owner

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

@JohelEGP
Copy link

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

@fcolecumberri
Copy link

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.

@reedhedges
Copy link

reedhedges commented Jun 26, 2023

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.

@lefticus lefticus changed the title 80% smaller code by preferring const How using const can dramatically improve code Sep 14, 2023
@lefticus
Copy link
Owner Author

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

@JohelEGP
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants