【发布时间】:2015-01-15 09:50:17
【问题描述】:
这是两个非常相似的Levenshtein Distance algorithms。
Swift 实现:
https://gist.github.com/bgreenlee/52d93a1d8fa1b8c1f38b
和Objective-C 实现:
https://gist.github.com/boratlibre/1593632
swift 的实现比ObjC 慢得多
我已经发送了几个小时以使其更快但是...似乎Swift 数组和Strings 操作不如objC 快。
在 2000 年 random Strings 计算 Swift 实现比 ObjC 慢大约 100(!!!) 倍。
老实说,我不知道可能出了什么问题,因为即使是 swift 的这一部分
func levenshtein(aStr: String, bStr: String) -> Int {
// create character arrays
let a = Array(aStr)
let b = Array(bStr)
...
比Objective C中的整个算法慢几倍
有人知道如何加快swift 的计算吗?
提前谢谢你!
追加
毕竟建议的改进 swift 代码看起来像这样。 在发布配置中它比 ObjC 慢 4 倍。
import Foundation
class Array2D {
var cols:Int, rows:Int
var matrix:UnsafeMutablePointer<Int>
init(cols:Int, rows:Int) {
self.cols = cols
self.rows = rows
matrix = UnsafeMutablePointer<Int>(malloc(UInt(cols * rows) * UInt(sizeof(Int))))
for i in 0...cols*rows {
matrix[i] = 0
}
}
subscript(col:Int, row:Int) -> Int {
get {
return matrix[cols * row + col] as Int
}
set {
matrix[cols*row+col] = newValue
}
}
func colCount() -> Int {
return self.cols
}
func rowCount() -> Int {
return self.rows
}
}
extension String {
func levenshteinDistanceFromStringSwift(comparingString: NSString) -> Int {
let aStr = self
let bStr = comparingString
// let a = Array(aStr.unicodeScalars)
// let b = Array(bStr.unicodeScalars)
let a:NSString = aStr
let b:NSString = bStr
var dist = Array2D(cols: a.length + 1, rows: b.length + 1)
for i in 1...a.length {
dist[i, 0] = i
}
for j in 1...b.length {
dist[0, j] = j
}
for i in 1...a.length {
for j in 1...b.length {
if a.characterAtIndex(i-1) == b.characterAtIndex(j-1) {
dist[i, j] = dist[i-1, j-1] // noop
} else {
dist[i, j] = min(
dist[i-1, j] + 1, // deletion
dist[i, j-1] + 1, // insertion
dist[i-1, j-1] + 1 // substitution
)
}
}
}
return dist[a.length, b.length]
}
func levenshteinDistanceFromStringObjC(comparingString: String) -> Int {
let aStr = self
let bStr = comparingString
//It is really strange, but I should link Objective-C coz dramatic slow swift performance
return aStr.compareWithWord(bStr, matchGain: 0, missingCost: 1)
}
}
malloc?? NSString??最后速度降低了 4 倍?有人需要swift吗?
【问题讨论】:
-
其他用户确认 Swift 数组真的很慢stackoverflow.com/questions/24567429/… 现在 Swift 不是 Beta。所以对我来说这看起来很奇怪。
-
2年了,这段代码还是很慢,没办法修复?
标签: objective-c arrays string performance swift