我不想结合两个字符串列表,它们都有200000多个项目。这是我用来组合它们的代码:
For Each item in list2
list1.add(item)
Next
但问题是将list2中的每个项目添加到list1需要很长时间。所以我问,是否有更好的解决方案来组合这些列表?
答案 0 :(得分:5)
List
类中有一个内置方法可以完全满足您的需求:
list1.AddRange(list2)
查看Microsoft页面here以查看其他信息。
无论如何,你真的确定你需要在内存中有这么多的字符串吗?
答案 1 :(得分:1)
我也很想知道需要,但如果你需要它们,可以考虑使用StringBuilder。我跑了一点测试:
Private Sub Button1_Click(sender As System.Object, _
e As System.EventArgs) Handles Button1.Click
Dim stpw1 As New Stopwatch
Dim stpw2 As New Stopwatch
'sample data
Dim ipsumA() As String = New String() {"Lorem", "ipsum", "dolor", "sit", _
"amet", "consectetur", "adipisicing", _
"elit", "sed", "do", "eiusmod", _
"tempor", "incididunt", "ut", "labore", _
"et", "dolore", "magna", "aliqua", "Ut", _
"enim", "ad", "minim", "veniam", "quis", _
"nostrud", "exercitation", "ullamco", _
"laboris", "nisi", "ut", "aliquip", "ex", _
"ea", "commodo", "consequat", "Duis", "aute", _
"irure", "dolor", "in", "reprehenderit", "in", _
"voluptate", "velit", "esse", "cillum", "dolore", _
"eu", "fugiat", "nulla", "pariatur", "Excepteur", _
"sint", "occaecat", "cupidatat", "non", "proident", _
"sunt", "in", "culpa", "qui", "officia", "deserunt", _
"mollit", "anim", "id", "est", "laborum"}
Dim list1 As New List(Of System.Text.StringBuilder)
Dim list2 As New List(Of System.Text.StringBuilder)
Debug.WriteLine("Approx. 200,000+ strings per list")
stpw2.Restart()
stpw1.Restart()
Do While list1.Count < 200000
For Each s As String In ipsumA
list1.Add(New System.Text.StringBuilder(s))
list2.Add(New System.Text.StringBuilder(s))
Next
Loop
stpw1.Stop()
Debug.WriteLine(stpw1.Elapsed.ToString)
stpw1.Restart()
list1.AddRange(list2)
stpw1.Stop()
stpw2.Stop()
Debug.WriteLine(stpw1.Elapsed.ToString)
Debug.WriteLine(stpw2.Elapsed.ToString)
End Sub
花了大约0.3秒,这是值得的。
答案 2 :(得分:1)
如果您事先知道列表的近似最大大小,请在构造函数中指定它。 List<T>
在内部使用数组来保存项目。如果没有指定尺寸,它的原始尺寸为4个。如果已满,则创建具有double size的新数组,并将旧数组的内容复制到新数组。对于40万件物品,这种情况多次发生!
var list1 = new List<string>(500000);