Friday, September 12, 2008

Add.Ovf

Writing high-performance applications is probably one of the most enthusiastic challenges a software developer can face. Nowadays, developing an application isn’t as hard as it was 10 years ago, mostly due to the appearance of managed environments (and tools improvement). But writing high-performance, multithread, extensible, expansible and scalable software is actually very challenging. Every detail counts.

Having said that, there’s one detail I haven’t paid much attention in the past: compiler flags (the other guidelines to write such software certainly can’t be learned from a blog). When using Visual Studio, creating a project, building and deploying it is very easy. But when building the project, the IDE actually uses a command line to build the project (for C#, “csc.exe”, for VB.NET “vbc.exe”) passing some parameters while others are default. Well, by default, the VB.NET compiler generates overflow checks for integer operations (both Debug and Release versions). The C# compiler doesn’t – you must specify that you want integer overflow checks (“csc.exe /checked” or in the properties of your Visual Studio project).

What is integer overflow check? An example from Derek Hatchard and Scott Swigart at MSDN:

(click to enlarge)

Quoting their explanation: “The code segments look equivalent (the extra C# variable loopLimit is used to match Visual Basic .NET behaviour, which is to copy max to a temporary local variable). Both methods require two integer addition operations – one for the increment of the sum variable and one for the increment of the loop counter. By default, the Visual Basic .NET compiler will generate the IL instruction add.ovf for these addition operations. The add.ovf instruction includes an overflow check and throws an exception if the sum exceeds the capacity of the target data type. By contrast, the default output of the C# compiler is the IL instruction add, which does not include an overflow check.”

Looking at the generated IL by both the compilers we can see the difference:

(click to enlarge)

(click to enlarge)

How about running the examples to compare the performance?

(click to enlarge)

As you can see when using integer overflow check there’s a big difference. If you set the VB compiler not to generate integer overflow checks the above VB.NET code will have the same performance as the C# version. You must be aware of details like these in order to “sharp” your application’s performance – and don’t say “I’m using C#” because that’s not the point!

Just as a final note, you can also force integer overflow checks for some operations using the C# keyword “checked”: http://msdn.microsoft.com/en-us/library/74b4xzyw.aspx