The Case of The More Complex C# Code Generate Better Assembly Code
More complex C# code will generate better assembly code? Really?
Notice the generated assembly code on the right side? You can see the code here.
And here is how the story began.
Once upon a time in Japan, I opened my GitHub homepage and saw this.
There is only a bunch of good news about .NET Core performance these days.
Unless you live under a rock (or dark matter developers?), you may have heard that .NET Core is ultra fast.
Congratulations. Now you know. You’re welcome.
Back to the story.
Here is the link to “Improve bool.TryFormat perf”: https://github.com/dotnet/coreclr/pull/18711/files.
Notice the uint
cast comment:
if ((uint)destination.Length > 3) // uint cast, per https://github.com/dotnet/coreclr/issues/18688
The first time I saw that uint
cast writing style was from Ben Adams’ blog, or to be exact: slide #21 of https://cdn.ageofascent.net/assets/2017/Corestart-Whats-new-performance-dotnet-core-2-0.pdf.
Okay, after looking around, then I saw this: https://github.com/dotnet/coreclr/commit/6ac136e313826833b7fd32f0c8968297e8d7458e
Following the link from the comment lead me to: https://github.com/dotnet/coreclr/issues/914
Who’d have thought that more complex C# code will produce better assembly code?
Wow. So I learned something today!
Kudos to https://github.com/mikedn, Stephen Toub, Ben Adams. Kudos to Jan Kotas for showing up in my GitHub homepage activity feed in the first place 😉. Well, kudos to all that involved in those conversation.
This is one of an example of how OSS can benefit us in improving our skills.
By looking around, we can learn a lot. I did contribute back, in the form of fixed some typos in corefx, dotnet-docker, HttpClientFactory, dotnet-api-docs, fixed broken links in dotnet-api-docs, also some trivial changes in ASP.NET benchmarks repo. If you are just looking around to learn something and found something that can be improved, don’t be afraid to send PRs! Sending a PR won’t kill your neighbor’s dog.
Another tip for learning and catching up with the trends (other than reading blogs, newsletters): follow great people on Twitter! In fact, I just really started using Twitter from December 2017. Better late than never.
Originally posted this on Twitter in Japanese.
Summary
Ternary operator returning true/false prevents redundant assembly code generation. So adding ? true: false
might lead to more keystrokes, longer code, but will have a better assembly code.