【发布时间】:2019-04-30 09:50:15
【问题描述】:
所以我被赋予了编写一个 vb 程序的任务,我在其中读取一个大的 .txt 文件(从 500mb 到 2GB 不等),这个文件通常以 13 位数字开头,然后在每行之后加载其他信息。 (例如“1578597500548 info info info info etc.”)我必须让用户输入一个 13 位数字,然后我的程序在每行开头搜索该数字的大文件,如果找到,则将整行写入新的 . txt文件!
我当前的程序运行良好,但我注意到我添加到列表/流阅读器部分占用了大约 90% 的处理时间。平均每次运行大约 27 秒。任何想法如何加快速度? 这是我写的。
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim wtr As IO.StreamWriter
Dim listy As New List(Of String)
Dim i = 0
stpw.Reset()
stpw.Start()
'reading in file of large data 700mb and larger
Using Reader As New StreamReader("G:\USER\FOLDER\tester.txt")
While Reader.EndOfStream = False
listy.Add(Reader.ReadLine)
End While
End Using
'have a textbox which finds user query number
Dim result = From n In listy
Where n.StartsWith(TextBox1.Text)
Select n
'writes results found into new file
wtr = New StreamWriter("G:\USER\searched-number.txt")
For Each word As String In result
wtr.WriteLine(word)
Next
wtr.Close()
stpw.Stop()
Debug.WriteLine(stpw.Elapsed.TotalMilliseconds)
Application.Exit()
End Sub
更新我已经接受了一些建议,不要先将其放入列表中,而只是在内存中搜索,时间大约快 5 秒,仍然需要 23 秒完成并且它写出我正在搜索的数字上方的行,所以如果你能告诉我我哪里出错了。谢谢大家!
wtr = New StreamWriter("G:\Karl\searchednumber.txt")
Using Reader As New StreamReader("G:\Karl\AC\tester.txt")
While Reader.EndOfStream = False
lineIn = Reader.ReadLine
If Reader.ReadLine.StartsWith(TextBox1.Text) Then
wtr.WriteLine(lineIn)
Else
Continue While
End If
End While
wtr.Close()
End Using
【问题讨论】:
-
当你只需要一行时,为什么要将整个文件加载到
listy?从用户那里获取输入,打开文件,然后开始一次读取一行并尝试匹配输入。如果不匹配,请将其扔掉并继续下一行。如果匹配,你已经得到了这条线,你就停止读取文件。 -
看到一个 13 位数字可能出现不止 1 次,因此必须搜索整个文件。
-
是的,当然,但是您现在正在将整个文件加载到内存中,然后您正在为查询创建这些字符串的枚举。您需要阅读每一行,并在匹配时将其存储。然后移动到下一个。不要存储不匹配的字符串。 LINQ 在这里不是你的朋友。
-
如果你想使用 LINQ,然后创建一个
List(Of String)用作可枚举源,使用 System.IO.File.ReadLines Method 将创建字符串迭代器。即Dim result = From n In System.IO.File.ReadLines("G:\USER\FOLDER\tester.txt"). -
更新到上面的新代码
标签: vb.net visual-studio visual-studio-2017 streamreader