What is the BigO of Swift's String.count?

前端 未结 3 1180
余生分开走
余生分开走 2021-01-03 05:08

When swift uses String.count is it:

O(n) where each time we call it we iterate through the entire String in order to count it

3条回答
  •  孤城傲影
    2021-01-03 05:32

    Looks like O(n) to me based on a quick Playground test.

    for step in 1...10 {
        let length = step * 100000
        let string = String(repeating: "x", count: length)
        let start = Date()
        let stringLength = string.count
        let end = Date()
        print("Length: \(stringLength), time: \(end.timeIntervalSince(start))")
    }
    
    // Length: 100000, time: 0.00178205966949463
    // Length: 200000, time: 0.00132298469543457
    // Length: 300000, time: 0.00184988975524902
    // Length: 400000, time: 0.00218689441680908
    // Length: 500000, time: 0.00302803516387939
    // Length: 600000, time: 0.00368499755859375
    // Length: 700000, time: 0.0039069652557373
    // Length: 800000, time: 0.00444602966308594
    // Length: 900000, time: 0.0052180290222168
    // Length: 1000000, time: 0.00539696216583252
    

提交回复
热议问题