We've all seen apps that display a list of tasks being processed by the app. As lines
are added to the list, it automatically scrolls to keep the last item visible.
The question here is which methodology would be more efficient, use a textbox and append
the new text to its text property and use the scrolltocaret method? Or use a listbox and
add new items to the list?
The Listbox will perform better. The Textbox.Text property is a string and
strings are immutable. Each time you perform an operation on a string - like
append, replace, trim - .NET copies the entire string into a new buffer and
returns a new string object to replace the old one.
Listbox.Items is
simply a list of pointers to objects. Adding more objects means adding four
bytes to the end of the list.
Here's the sample code comparing the two methodologies:
Public Class Form1
Inherits System.Windows.Forms.Form
'blah blah blah the things the are added automatically go here
Public Function addText(ByVal newText As String)
'Is it first item on the list? If so, do not add linefeed
If TextBox1.TextLength = 0 Then
TextBox1.Text = newText
Else
'I could use string builder here, but I am lazy
TextBox1.Text = TextBox1.Text + Chr(13) + Chr(10) + newText
End If
TextBox1.SelectionStart = TextBox1.TextLength - 1
TextBox1.ScrollToCaret()
End Function
Public Function addList(ByVal newItem As String)
'Use the begin and end update to avoid flicker
ListBox1.BeginUpdate()
ListBox1.Items.Add(newItem)
ListBox1.SetSelected(ListBox1.Items.Count - 1, True)
ListBox1.EndUpdate()
End Function
Private Sub butAddLst1K_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles butAddLst1K.Click
'Adds 1000 items to the list
Dim t As Int16
For t = 1 To 1000
addList("Item #" + t.ToString())
Next
End Sub
Private Sub butAddLst1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles butAddLst1.Click
'Adds 1000 items to the list
addList("One more Item")
End Sub
Private Sub butAddTxt1K_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles butAddTxt1K.Click
'Add 1000 'items' to the textbox
Dim t As Int16
For t = 1 To 1000
addText("Item #" + t.ToString())
Next
End Sub
Private Sub butAddTxt1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles butAddTxt1.Click
'Add 1 'item' to the textbox
addText("One More Item")
End Sub
end class
from a solution provided by Ric Parodi and Keith Payne in Messages #1026018, 1026245
Ric supplied the code sample, Keith supplied the answer to the question.
|