VB.net ReDim Preserve 的替代方式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17860138/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VB.net Alternative way of ReDim Preserve
提问by Marc Intes
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.
我的程序确实可以工作,但我认为它存在性能问题,它在循环数组时消耗了我总 CPU 使用量的 40%。通常我的程序只会消耗不到 5% 的 CPU 使用率,我认为 ReDim Preserve 是导致这种情况的原因,因为我正在循环大约 100,000+ 行。这是我的代码。
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.
除了 ReDim Preserve 之外,还有其他方法可以将值放入数组中吗?提前致谢,我现在真的被这个问题困住了。
Here is now my updated code using List.
这是我使用 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.
我仍然需要数组的功能,所以我创建了一个数组并将 List 的内容放入其中。
回答by SLaks
You should use a List(Of String), which will leave room for future elements instead of resizing every time.
您应该使用 a List(Of String),这将为未来的元素留出空间,而不是每次都调整大小。
回答by David Sdot
As SLaks said best should be a List:
正如 SLaks 所说,最好的应该是一个列表:
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()
回答by the_lotus
Is seems like you are reading a file, an other option would be to use the ReadAllLinesmethod.
似乎您正在读取文件,另一种选择是使用ReadAllLines方法。
Dim sArray() As String = System.IO.File.ReadAllLines("messages.txt")

