我有两个带有 float 的大型(数千个值)数组,我想将它们组合成一个 xy 点数组以进行进一步处理,例如绘图。
所以现在在 Xcode Playground 上我正在这样做:
let xArray = // read from datafile, fast
let yArray = // read from another datafile, fast
struct xyPoint {
let x: Float
let y: Float
}
var spectrum: [xyPoint] = []
for i in 0..<xArray.count {
let xy = xyPoint(x: xArray[i], y: yArray[i])
spectrum.append(xy)
}
现在当我运行 playground 时,这需要很长时间才能完成。
有什么办法可以加快速度吗?
最佳答案
我检查了针对您的问题的各种解决方案的性能。你可以从 this link to github 下载我的测试
A) 你的代码
var spectrum: [XYPoint] = []
for i in 0..<xArray.count {
let xy = XYPoint(x: xArray[i], y: yArray[i])
spectrum.append(xy)
}
B) zip + map ( Martin R's answer )
let spectrumB = zip(xArray, yArray).map(XYPoint.init)
C)范围+ map (我的解决方案)
let spectrum = (0 ..< xArray.count).map { i in
return XYPoint(x: xArray[i], y: yArray[i])
}
D) ReserveCapacity + 追加 ( Duncan C's answer )
var spectrum: [XYPoint] = []
spectrum.reserveCapacity(xArray.count)
for (index, value) in xArray.enumerated() {
spectrum.append(XYPoint(x: xArray[index], y: yArray[index]))
}
我的结果(以秒为单位)
╭──────────────┬──────────────┬──────────────┬──────────────╮
│ A │ B │ C │ D │
╭───────────╬══════════════╪══════════════╪══════════════╪══════════════╡
│ 100 ║ 0.000009426 │ 0.000002401 │ 0.000000571 │ 0.000000550 │
│ 200 ║ 0.000003356 │ 0.000002629 │ 0.000000911 │ 0.000000866 │
│ 500 ║ 0.000005610 │ 0.000007288 │ 0.000002236 │ 0.000002012 │
│ 1000 ║ 0.000010638 │ 0.000009181 │ 0.000003905 │ 0.000005030 │
│ 2000 ║ 0.000019377 │ 0.000013316 │ 0.000007116 │ 0.000008732 │
│ 5000 ║ 0.000023430 │ 0.000019304 │ 0.000019809 │ 0.000019092 │
│ 10000 ║ 0.000050463 │ 0.000031669 │ 0.000035121 │ 0.000035420 │
│ 20000 ║ 0.000087040 │ 0.000058664 │ 0.000069300 │ 0.000069456 │
│ 50000 ║ 0.000272357 │ 0.000204213 │ 0.000176962 │ 0.000192996 │
│ 100000 ║ 0.000721436 │ 0.000459551 │ 0.000415024 │ 0.000437604 │
│ 200000 ║ 0.001114534 │ 0.000924621 │ 0.000816374 │ 0.000896202 │
│ 500000 ║ 0.002576687 │ 0.002094998 │ 0.001860833 │ 0.002060462 │
│ 1000000 ║ 0.007063596 │ 0.005924892 │ 0.004319181 │ 0.004869024 │
│ 2000000 ║ 0.014474969 │ 0.013594134 │ 0.008568550 │ 0.009388957 │
│ 5000000 ║ 0.038348767 │ 0.035136008 │ 0.021276415 │ 0.023855382 │
│ 10000000 ║ 0.081750925 │ 0.078742713 │ 0.043578664 │ 0.047700495 │
│ 20000000 ║ 0.202616669 │ 0.199960563 │ 0.148141266 │ 0.145360923 │
│ 50000000 ║ 0.567078563 │ 0.552158644 │ 0.370327555 │ 0.397115294 │
│ 100000000 ║ 1.136993625 │ 1.101725386 │ 0.713406642 │ 0.740150322 │
└───────────╨──────────────┴──────────────┴──────────────┴──────────────┘
关于arrays - Swift 性能中的 xy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45509884/