【问题标题】:Reduce to concatenate String Array? Faster solution?减少连接字符串数组?更快的解决方案?
【发布时间】:2020-03-19 21:07:26
【问题描述】:

我使用这样的代码从一个字符串数组构建一个字符串:

class ActionCMD {   // "class" to avoid value copies when updating string members
    var cmds = [String]()   // simply the list of all strings to speed up inserting
    var cmd : String { return cmds.reduce("", +) }   // resulting string
}

但是对于 35.000 个字符串,它需要 15 分钟。有没有更好(更快)的方法来进行连接?

【问题讨论】:

  • return cmds.joined()怎么样
  • 如何获得输入集 35000 String?也许可以进行一些预处理以加快速度
  • 是不是这段代码需要 15 分钟而不是加载 35,000 个字符串?
  • 在操场上执行你的代码 reduce 对我来说在几年前的 MacBook Pro 上需要 0.0003 秒,所以即使我的测试远非精确,我觉得问题必须出在其他地方你

标签: arrays swift string concatenation reduce


【解决方案1】:

您应该避免创建中间字符串。相反,可以使用以下任一方法改变先前累积的字符串:

cmds.reduce(into: "", { $0 += $1 })

或:

cmds.joined()

或者简单地说:

var cmd = ""
for i in cmds.indices {
    cmd += cmds[i]
}

更多关于字符串连接here

【讨论】:

  • 谢谢,我会尝试“加入”。我不使用循环来自己做。喜欢使用库函数。
  • 它现在很快! :-) 我认为是 30 秒而不是分钟!非常感谢。
  • @Peter71 差别很大!很高兴我能帮上忙:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-29
  • 2012-01-24
  • 2023-01-24
  • 2011-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多