The Case of The More Complex C# Code Generate Better Assembly Code

More complex C# code will generate better assembly code? Really?

Joni 【ジョニー】
3 min readJul 1, 2018

[Japanese version]

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.

My GitHub homepage activity feed

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.

PR by Ben Adams: “Use string.IsNullOrEmpty to eliminate bounds check to first char”

Following the link from the comment lead me to: https://github.com/dotnet/coreclr/issues/914

Comment from “mikedn”

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.

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.

--

--