这是我的解决方案:
Public Shared Function FastSplit(inputString As String, separator As String) As String()
Dim kwds(1) As String
Dim k = 0
Dim tmp As String = ""
For l = 1 To inputString.Length - 1
tmp = Mid(inputString, l, 1)
If tmp = separator Then k += 1 : tmp = "" : ReDim Preserve kwds(k + 1)
kwds(k) &= tmp
Next
Return kwds
End Function
这是一个带有基准测试的版本:
Public Shared Function FastSplit(inputString As String, separator As String) As String()
Dim sw As New Stopwatch
sw.Start()
Dim kwds(1) As String
Dim k = 0
Dim tmp As String = ""
For l = 1 To inputString.Length - 1
tmp = Mid(inputString, l, 1)
If tmp = separator Then k += 1 : tmp = "" : ReDim Preserve kwds(k + 1)
kwds(k) &= tmp
Next
sw.Stop()
Dim fsTime As Long = sw.ElapsedTicks
sw.Start()
Dim strings() As String = inputString.Split(separator)
sw.Stop()
Debug.Print("FastSplit took " + fsTime.ToString + " whereas split took " + sw.ElapsedTicks.ToString)
Return kwds
End Function
以下是一些关于相对较小但大小不一的字符串的结果,最多为 8kb 块。 (时间以刻度为单位)
FastSplit 耗时 8,而拆分耗时 10
FastSplit 耗时 214,而拆分耗时 216
FastSplit 耗时 10 而拆分耗时 12
FastSplit 需要 8 次,而拆分需要 9 次
FastSplit 耗时 8,而拆分耗时 10
FastSplit 耗时 10 而拆分耗时 12
FastSplit 耗时 7,而拆分耗时 9
FastSplit 耗时 6,而拆分耗时 8
FastSplit 耗时 5,而拆分耗时 7
FastSplit 耗时 10,而拆分耗时 13
FastSplit 耗时 9,而拆分耗时 232
FastSplit 耗时 7,而拆分耗时 8
FastSplit 需要 8 次,而拆分需要 9 次
FastSplit 耗时 8,而拆分耗时 10
FastSplit 耗时 215,而拆分耗时 217
FastSplit 耗时 10,而拆分耗时 231
FastSplit 耗时 8,而拆分耗时 10
FastSplit 耗时 8,而拆分耗时 10
FastSplit 耗时 7,而拆分耗时 9
FastSplit 耗时 8,而拆分耗时 10
FastSplit 耗时 10,而拆分耗时 1405
FastSplit 耗时 9,而拆分耗时 11
FastSplit 耗时 8,而拆分耗时 10
另外,我知道有人会阻止我使用 ReDim Preserve 而不是使用列表...原因是,列表在我的基准测试中确实没有提供任何速度差异,所以我回到了“简单”的方式.