Home > Mobile >  Swift Dictionary is slow?
Swift Dictionary is slow?

Time:10-28

Situation: I was solving LeetCode 3. Longest Substring Without Repeating Characters, when I use the Dictionary using Swift the result is Time Limit Exceeded that failed to last test case, but using the same notion of code with C it acctually passed with runtime just fine. I thought in swift Dictionary is same thing as UnorderdMap.

Some research: I found some resources said use NSDictionary over regular one but it requires reference type instead of Int or Character etc.

Expected result: fast performance in accessing Dictionary in Swift

Question: I know there are better answer for the question, but the main goal here is Is there a effiencient to access and write to Dictionary or someting we can use to substitude.

func lengthOfLongestSubstring(_ s: String) -> Int {
        var window:[Character:Int] = [:] //swift dictionary is kind of slow?
        let array = Array(s)
        var res = 0
        var left = 0, right = 0
        while right < s.count {
            let rightChar = array[right]
            right  = 1
            window[rightChar, default: 0]  = 1
            while window[rightChar]! > 1 {
                let leftChar = array[left]
                window[leftChar, default: 0] -= 1
                left  = 1
            }
            res = max(res, right - left)
        }
        return res
    }

CodePudding user response:

Because complexity of count in String is O(n), so that you should save count in a variable. You can read at chapter Strings and Characters in Swift Book

Extended grapheme clusters can be composed of multiple Unicode scalars. This means that different characters—and different representations of the same character—can require different amounts of memory to store. Because of this, characters in Swift don’t each take up the same amount of memory within a string’s representation. As a result, the number of characters in a string can’t be calculated without iterating through the string to determine its extended grapheme cluster boundaries. If you are working with particularly long string values, be aware that the count property must iterate over the Unicode scalars in the entire string in order to determine the characters for that string.

The count of the characters returned by the count property isn’t always the same as the length property of an NSString that contains the same characters. The length of an NSString is based on the number of 16-bit code units within the string’s UTF-16 representation and not the number of Unicode extended grapheme clusters within the string.

  • Related