article

Tips to faster codes in VB .Net

Email
Submitted on: 4/25/2016 8:31:50 AM
By: Salem Al Shekaili 
Level: Beginner
User Rating: Unrated
Compatibility: VB.NET
Views: 1841
 
     Although different codes could achieve same goal, they may be the same in their performance. Here are some tips for better code in term of performance.

 
				Imports System.Text
Module Module1
Sub Main()
 
'1. Use Integer array instead of List(of Int32) 
Dim li As List(Of Int32) = New List(Of Integer)()
Dim sw As New Stopwatch()
sw.Start()
For i As Integer = 0 To 9999
li.Add(i)
Next i
sw.Stop()
Console.Write("Using list(of Int32)" & sw.ElapsedTicks & Environment.NewLine)
sw.Reset()
sw.Start()
Dim a(9999) As Int32
For i As Integer = 0 To 9999
a(i) = i
Next i
sw.Stop()
Console.Write("Using Value(Integer Array)" & sw.ElapsedTicks & Environment.NewLine)
'2. Use For loop instead of foreach
Dim Count As List(Of Int32) = New List(Of Integer)()
Dim lst1 As List(Of Int32) = New List(Of Int32)()
Dim lst2 As List(Of Int32) = New List(Of Int32)()
For i As Integer = 0 To 9999
Count.Add(i)
Next
sw.Reset()
sw.Start()
For i As Integer = 0 To Count.Count - 1
lst1.Add(i)
Next i
sw.Stop()
Console.Write("For Loop :- " & sw.ElapsedTicks & Environment.NewLine)
sw.Restart()
For Each number As Integer In Count
lst2.Add(number)
Next
sw.Stop()
Console.Write("Foreach Loop:- " & sw.ElapsedTicks & Environment.NewLine)
'3. Always use Stringbuilder for String concatenation operations
Dim First As String = "A"
Dim sb As New StringBuilder("A")
Dim st As New Stopwatch()
st.Start()
For i As Integer = 0 To 499
First = First & "A"
Next i
st.Stop()
Console.WriteLine("Using String :-" & st.ElapsedTicks)
st.Restart()
For i As Integer = 0 To 499
sb.Append("A")
Next i
st.Stop()
Console.WriteLine("Using Stringbuilder :-" & st.ElapsedTicks)
Console.ReadLine()
End Sub
End Module


Other 7 submission(s) by this author

 


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Beginner category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments


 There are no comments on this submission.
 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)
 

To post feedback, first please login.