Mark Mintoff My superpower is common sense


Benchmarking Infinite Loops


Today, my good friend Andrew Calleja and I set about discussing infinite loops and which technique for infinite loops would be the most efficient. Our choices boiled down to four:

  • for( ; ; )
  • while(true)
  • while(1==1)
  • GOTO loop

I created a small program to perform a benchmark test and the discrepancy between the four techniques was negligible enough to attribute to other operations in the background, so we agreed that we would have to look into the CIL using ILSpy. What was discovered was very, very interesting. First and foremost, the loops are programmed as follows:

After opening the .exe file in ILSpy, I noticed that all of the above were converted into while(true) loops!!

However, when I switched the language from C# to IL:

As can clearly be seen, the GOTO loop gets compiled into the shortest IL. Additionally the GOTO loop does not create a superfluous boolean. Quite interesting!

Please note that this IL was generated when the program was compiled in Debug mode. When generating the IL in Release mode, the loops all generate the same IL:

VN:F [1.9.22_1171]
Rating: 0.0/5 (0 votes cast)