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 TextBox.AppendText instead of concatenating strings

From Wiki

Jump to: navigation, search

Run the following code in a windowsformsapplication.

Make a form and add three textboxes and 3 labels to it.

then add this code in the code window

  1. Imports System.Text
  2.  
  3. Public Class Form1
  4.     Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  5.         Dim str As New StringBuilder()
  6.         Dim begin As DateTime = Now
  7.         For i As Integer = 0 To 100000
  8.             str.Append("a")
  9.             str.Append(i.ToString)
  10.         Next
  11.         TextBox1.Text = str.ToString
  12.         Label1.Text = "Code took : " & (Now - begin).Milliseconds & " milliseconds"
  13.         Dim str1 As String = ""
  14.         begin = Now
  15.         For i As Integer = 0 To 100000
  16.             str1 &= "a" & i.ToString
  17.         Next
  18.         TextBox2.Text = str1
  19.         Label2.Text = "Code took : " & (Now - begin).Milliseconds & " milliseconds"
  20.         begin = Now
  21.         For i As Integer = 0 To 100000
  22.             TextBox3.AppendText("a")
  23.             TextBox3.AppendText(i.ToString())
  24.         Next
  25.         TextBox3.Text = str1
  26.         Label3.Text = "Code took : " & (Now - begin).Milliseconds & " milliseconds"
  27.     End Sub
  28. End Class


This is the result.

Image:Appendtext.jpg

And allthough the stringbuilder code is still faster the appendtext code is also faster then just concatenation and uses less code. So go for that as much as you can.

Disclaimer: This code was only tested in Visual Studio 2008.

349 Rating: 1.3/5 (4 votes cast)