VB.NET Performance Optimizations
OK, kicked into gear by a GDN posting on ‘Is VB.NET is slower than C#’, based on some of the comments, I decided to dig into some of the points a bit deeper. This, of course, led to some interesting discoveries and even more questions.
One point that was brought up is that C# does string comparisons very different than VB.NET. This is true, however, the same performance can be gained if you know how (and why) VB.NET does it and optimize accordingly. This issue is that VB.NET is able to turn on Option Compare Binary or Option Compare Text. Doing so will control how strings are compared to one another. The Text option will take into account locale information. C#, however, uses the operator overloaded method of the string object to do it’s comparison. Digging a little deeper, the overloaded operator then uses the Equals method to actually do the comparison. To improve VB.NET’s string comparison, it’s as simple as changing from using the equals sign to using the Equals method (and technically, C# could improve it’s performance as well by doing the same).
Now, exactly what does this mean in the end. Well, I ran a couple of pretty quick and dirty tests to see how much of a performance gain one could see. Bear in mind, like all of these tests, take them with a grain of salt and do your own tests taking your environment into account.
Using the following code:
1
2
3
4
5
6
7
Dim t As Long = Now.Ticks
For i As Integer = 1 To 1000000
If Now.ToString = Now.ToString Then
End If
Next
t = Now.Ticks - t
MsgBox("Took " & (t / 10000000) & " seconds.")
This will cause 1,000,000 checks against two strings that will be changing every second. What is being compared is less important in this test than the method being used. The next test, we’ll just modify the following test for equality line to the following:
1
If Now.ToString.Equals(Now.ToString) Then
The results I got were pretty consistent at around 16.25 and 14.16 seconds respectively. The results are pretty measurable, a little over two second difference between the two methods.
Now, I do have to jump in here and point out a couple of things. First off, it takes a pretty sizable about of comparisons to get this type of result. Secondly, I really don’t think that this would ever actually be a factor in a real application, since whatever method you are using to actually get the data (1,000,000 items) will probably take a lot longer than the string comparisons would add to your final result. For example, if you were evaluating a million records from a database, the 2 seconds added to that overall process will not make much of a difference. Even reading a million items from a binary file on the hard drive, I still can’t imagine that the 2 seconds would make much of a difference. I’m sure there are cases where this would be a factor, but for the 95% of the applications being developed, probably not. ;-)