Swift - 正则表达式与组件/连接 : which is more efficient for String operations

标签 swift regex string

我需要删除 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/

相关文章:

json - 如何使用这个 JSON 响应?

swift - 更新到 Swift 2.0 后 NSURLConnection 抛出

javascript - 用于替换特定单词的正则表达式

C# 正则表达式 - 替换为自身

c - 没有 strcmp() 的字符串比较

swift - '(键 : String, 值:任何 )' is not convertible to ' [字符串:任何]'

swift - 用于字数计算的 Swift String 中的字数

javascript - 正则表达式 url 获取路径名后的所有内容

Python String 到列表处理

C++ zlib 压缩文件中的字符串