Login or Sign Up to become a member!
LessThanDot Sit Logo

LessThanDot

Community Wiki

Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.

LTD Social Sitings

Lessthandot twitter Lessthandot Linkedin Lessthandot friendfeed Lessthandot facebook Lessthandot rss

Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.

Navigation

Google Ads

USe Stringbuilder to concatenate strings

From Wiki

Jump to: navigation, search

In VB.Net strings are immutable (see wikipedia:Immutable_object for a better explanation). This means that concatenation can be expensive.

This is what we understand with bad concatenation.

  1. Dim str As String = ""
  2.         str = str & "a"
  3.         Console.WriteLine(str)
  4.         str = str & "b"
  5.         Console.WriteLine(str)
  6.         Console.ReadLine()

This will result in this on our console

a ab

off course there is also a shorter version of this

  1. Dim str As String = ""
  2.         str &= "a"
  3.         Console.WriteLine(str)
  4.         str &= "b"
  5.         Console.WriteLine(str)
  6.         Console.ReadLine()

which will show the same result as above.

Doing the above in small numbers isn't all that bad you will loose miliseconds if not less per iteration.

But what happens if you do this.

  1. Dim str1 As String = ""
  2.         begin = Now
  3.         Console.WriteLine("Code started at : " & begin)
  4.         For i As Integer = 0 To 100000
  5.             str1 &= "a" & i.ToString
  6.         Next
  7.         Console.WriteLine("Code ended at : " & Now)
  8.         Console.WriteLine("Code took : " & (Now - begin).Milliseconds & " milliseconds")
  9.         Console.ReadLine()

This takes 5115 milliseconds on my computer.

Can we do better?

Yes.

The next version uses A Stringbuilder. The Stringbuilder can be found in the System.Text library. So you will have to import that.

  1. Dim str As New StringBuilder()
  2.         Dim begin As DateTime = Now
  3.         Console.WriteLine("Code started at : " & begin)
  4.         For i As Integer = 0 To 100000
  5.             str.Append("a")
  6.             str.Append(i.ToString)
  7.         Next
  8.         Console.WriteLine("Code ended at : " & Now)
  9.         Console.WriteLine("Code took : " & (Now - begin).Milliseconds & " milliseconds")
  10.         Console.ReadLine()

This code only took 78 miliseconds to run on my computer so it's over a hundred times faster.


Disclaimer: The code above was only tested in Visual studio 2008 console application.

343 Rating: 3.4/5 (5 votes cast)