我怀疑性能问题是由于创建了大量的大型中间字符串。因此,任何不创建中间字符串或使用更少的字符串的方法都会表现得更好。
正则表达式替换很有可能。
Option Explicit
Sub Test(ByVal text As String)
Static Regex As Object
If Regex Is Nothing Then
Set Regex = CreateObject("VBScript.RegExp")
Regex.Global = True
Regex.MultiLine = True
End If
Regex.Pattern = " +" ' space, one or more times
Dim result As String: result = Regex.Replace(text, " ")
Debug.Print Len(result), Left(result, 20)
End Sub
输入 4500 万个字符的字符串大约需要一秒钟。
跑步者:
Sub Main()
Const ForReading As Integer = 1
Const FormatUTF16 As Integer = -1 ' aka TriStateTrue
Dim fso As Object: Set fso = CreateObject("Scripting.FileSystemObject")
Dim file As Object: Set file = fso.OpenTextFile("C:\ProgramData\test.txt", ForReading, False, FormatUTF16)
Dim text As String: text = file.ReadAll()
Set file = Nothing
Set fso = Nothing
Debug.Print Len(text), Left(text, 20)
Test (text)
End Sub
测试数据创建者(C#):
var substring = "××\n× ×× ";
var text = String.Join("", Enumerable.Repeat(substring, 45_000_000 / substring.Length));
var encoding = new UnicodeEncoding(false, false);
File.WriteAllText(@"C:\ProgramData\test.txt", text, encoding);
顺便说一句——由于 VBA(VB4、Java、JavaScript、C#、VB 等)使用 UTF-16,因此空格字符是一个 UTF-16 代码单元 ChrW(32)。 (任何与 ASCII 的相似或比较都是不必要的脑力操,如果放入代码为 ANSI [Chr(32)],则在幕后进行不必要的转换,对于不同的机器、用户和时间会有不同的行为。)