Marc Intes
Marc Intes

Reputation: 737

VB.net Alternative way of ReDim Preserve

my program does work but i think it suffers performance issues, it is consuming upto 40% of my total CPU usage while it is looping the array. normally my programs would only consume under 5% of CPU usage, i think ReDim Preserve is causing this as i am looping around 100,000+ of lines. here is my code.

    Dim sArray As String()
    Dim fStream As New System.IO.FileStream("messages.txt", IO.FileMode.Open)
    Dim sReader As New System.IO.StreamReader(fStream)
    Dim Index As Integer = 0
    Do While sReader.Peek >= 0
        ReDim Preserve sArray(Index)
        sArray(Index) = sReader.ReadLine
        Index += 1
    Loop

    fStream.Close()
    sReader.Close()

Is there any alternative way of placing values into an array aside from ReDim Preserve? Thanks in advance, i am really trapped into this problem right now.

Here is now my updated code using List.

    Dim sArray As String()
    Dim sList As New List(Of String)
    Dim fStream As New System.IO.FileStream("messages.txt", IO.FileMode.Open)
    Dim sReader As New System.IO.StreamReader(fStream)
    Dim Index As Integer = 0
    Do While sReader.Peek >= 0
        sList.Add(sReader.ReadLine)
    Loop
    sArray = sList.ToArray

    fStream.Close()
    sReader.Close()

I still needed the funcionalities of an array so i created an array and placed the contents of the List into it.

Upvotes: 0

Views: 13168

Answers (3)

the_lotus
the_lotus

Reputation: 12748

Is seems like you are reading a file, an other option would be to use the ReadAllLines method.

Dim sArray() As String = System.IO.File.ReadAllLines("messages.txt")

Upvotes: 1

David Sdot
David Sdot

Reputation: 2333

As SLaks said best should be a List:

Dim sArray As New List(Of String)
Dim fStream As New System.IO.FileStream("messages.txt", IO.FileMode.Open)
Dim sReader As New System.IO.StreamReader(fStream)
Do While sReader.Peek >= 0
    sArray.add(sReader.ReadLine)
Loop

fStream.Close()
sReader.Close()

Upvotes: 3

SLaks
SLaks

Reputation: 887413

You should use a List(Of String), which will leave room for future elements instead of resizing every time.

Upvotes: 6

Related Questions