Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift vs Python Performance

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?

like image 284
Jeff Zacharias Avatar asked Mar 03 '26 20:03

Jeff Zacharias


1 Answers

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)
    }
}
like image 185
Jeff Zacharias Avatar answered Mar 06 '26 09:03

Jeff Zacharias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!