Just like the popular view, I thought lesser code means better performance.
I tested:
againstvb.net Code:
value = CType(object, ObjectType).Property
The first method doesn't need an intermediate variable in between to store my object. This should also put less burden on the garbage collector as there is no variable. The 2nd way has an intermediate variable required in memory. So I thought it must be faster using the first way rather than the second way. But test results shows just the opposite here.vb.net Code:
Dim obj As ObjectType = CType(object, ObjectType) value = obj.Property
vb.net Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim sw As New Stopwatch, senderName As String For i As Integer = 1 To 5 sw.Reset() : sw.Start() For j As Integer = 1 To 100000000 senderName = CType(sender, Button).Name Next sw.Stop() Debug.Print("One Line : " & sw.ElapsedMilliseconds) sw.Reset() : sw.Start() For j As Integer = 1 To 100000000 Dim btn As Button = CType(sender, Button) senderName = btn.Name Next sw.Stop() Debug.Print("Two Lines: " & sw.ElapsedMilliseconds) Next End Sub
This is the result:
Anyone know why this happens? Is the CLR doing some smart optimizations?Code:One Line : 3786 Two Lines: 3677 One Line : 3787 Two Lines: 3683 One Line : 3787 Two Lines: 3677 One Line : 3790 Two Lines: 3678 One Line : 3783 Two Lines: 3677
Pradeep![]()




icon on the left of the post.
Reply With Quote