I have some code in Python that builds a dictionary of about 250K strings (words) as keys with each value having an array of strings. The Python version runs in about 0.5 seconds. I needed to port this to Swift but my Swift port runs in 10.1 seconds, 20 times slower.
Here is the Python code:
wordsDictionary = defaultdict(list)
for word in words:
wordsDictionary[sort_string(word)].append(word)
And here is the Swift code:
var wordsDictionary : Dictionary<String, [String]> = Dictionary()
for word in words {
let sortedWord : String = String(word.characters.sort())
if wordsDictionary[sortedWord] == nil {
wordsDictionary[sortedWord] = []
}
wordsDictionary[sortedWord]?.append(word)
}
Is there any way to speed up the Swift version or are Swift dictionaries still that much slower than Python?
After changing the string sort and array allocation for the dictionary, here is my final code that executes 1.4s.
var wordsDictionary : Dictionary<String, [String]> = Dictionary()
for word in words {
let sortedWordUTF8 = word.utf8.sort()
let sortedWord : String = NSString(bytes: sortedWordUTF8, length: sortedWordUTF8.count, encoding: NSUTF8StringEncoding) as! String
if wordsDictionary[sortedWord] == nil {
wordsDictionary[sortedWord] = [word]
}
else {
wordsDictionary[sortedWord]!.append(word)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With