Readable code and compiler optimization

Most comments on my code during reviews are about optimization. Tools like Resharper suggest code changes for cleaner code and optimization. But what about readability? Are most of today’s compilers smart enough to optimize the code?

The sample code below writes output to the console when writeToFile is false. Both lines do the same, but I prefer the first as it is more readable (to me).

if (false == writeToFile) Console.WriteLine("Whatever");
// OR
if (! writeToFile) Console.WriteLine("Whatever");

With ILDASM the IL code is read from the compiled assembly. The code is exactly the same. Looks like the compiler is smart enough for this case.

Back in the day I learned C++. One of the program tests was the for statement. See the C# code below with that mindset. The first line got you flunked, the second was 1 point, the third got you 5 points and the last the full 10 points.

for (int i = 0; i < 10; i = i + 1) Console.WriteLine("output");
for (int i = 0; i < 10; i += 1) Console.WriteLine("output");
for (int i = 0; i < 10; i ++) Console.WriteLine("output");
// Below is different!
for (int i = 0; i ++ < 10; ) Console.WriteLine("output");

Again getting the IL code from the assembly showed the first three lines resulted in the same code, where the last was different.
Debugging the code will show the behavior is slightly different (hint: when is the index incremented) So be warned not to optimize the code so it changes behavior!

I’ll be programming my code for readability no matter what the tools suggest.

About erictummers

My work as a recruited developer changes almost every month. I like challenges and sharing the solutions with others. On my blog I’ll mostly post about my work, but expect an occasional home project, productivity tip and tooling review.
This entry was posted in Development and tagged , , . Bookmark the permalink.

One Response to Readable code and compiler optimization

  1. jokelab says:

    “Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.”
    – Martin Golding

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s