Post

Performance Improvement - CInt(Fix(value))

From the Visual Studio 2017 15.8 Release Notes

Visual Basic Performance Improvement

Visual Basic now provides a significant performance improvement when using the pattern CInt(Fix(number)) to convert from non-integer types to integers.

Although this won’t be noticed by many VB developers; it will be noticed by some who are working on some very niche type projects such as applications that are processing graphics files, emulation, etc. Anything where there is a ton of floating-point to whole-number conversion taking place. The improvement is basically optimizing this pattern so that it short-circuits to a single IL operation… so it literally can’t get any faster (at least not in .NET terms). I should also note that this could have a serious performance impact (improvement) for any ASP.NET applications that utilize this pattern; I should also point out that any code that is converted from C# to VB…

C#:

1
int a = (int)value;

VB:

1
Dim a = CInt(Fix(value))

If you just convert using CInt() (leaving Fix() out) the result can be far from what was originally executing with C# as CInt() will potentially round the result where C# doesn’t. In other words, if the value was 9.9 in C#, the a would result in 9; wherein VB, the value of 9.9 results in 10. When you include Fix(), the final result of the conversion matches what C# produces. This isn’t meant to be an argument as to which is better (I mean, to me 9.9 is closer to 10, not 9, but hey, I did say this wasn’t meant to be an argument); but rather the difference and how to get to the same result. Here’s where the pre-performance-improvement created a bit of a problem… in order to get the same result, it took a significantly longer amount of time. Right or wrong, the difference is results in any code converted from C# to VB to potentially display as being “slower”. As a VB developer, you’d have to spend some time evaluating whether or not it was safe to refactor the code in order to increase the overall performance of the code.

Is this very discoverable? No. Does that matter? No. Everyone benefits, whether or not they are even aware of this fact. ;-)

Most people won’t know that this gem even exists (nor should they care). However, you do. You’re welcome. :-D

A huge THANK YOU to the VB team!

This post is licensed under CC BY 4.0 by the author.