我需要删除 Swift 中单词之间的过多空格(给定字符串中的单词不会超过 5 个),不确定哪个更有效:正则表达式或普通组件和连接?
例如:
Hello world! My name is Tom.
结果:
Hello world! My name is Tom.
方法一:
let result = input.components(separatedBy: " ").filter { string -> Bool in
return string.isEmpty == false
}.joined(separator: " ")
方法2:
let result = input.replacingOccurrences(of: "[ \t]+", with: " ", options: .regularExpression, range: range)
最佳答案
我运行了一些性能测试,将罗密欧与朱丽叶的整个脚本逐行输入到两个函数(请参阅 online sample )。
我实际上有点惊讶,正则表达式替换几乎与组件/字符串操作相同:正则表达式仅慢约 2 倍:
| Approach | abs. running time | cpu time | Time to evaluate func | memory peak |
|-------------------|-------------------|----------|-----------------------|-------------|
| components/string | 0.21 sec | 0.2 sec | 0.11 sec | 9 Mb |
| regex replace | 0.33 sec | 0.36 sec | 0.21 sec | 34 Mb |
这没有多大意义。唯一明显的区别可能是峰值内存消耗。但即使您在合理数量的并行循环中运行正则表达式替换,它也应该没问题。尽管如此,请始终使用真实代码运行您自己的测试。
然而,底线如 rmaddy 所评论。
Use the code you prefer and find easier to read and maintain.
关于Swift - 正则表达式与组件/连接 : which is more efficient for String operations,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50920798/