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?