Skip to content

Instantly share code, notes, and snippets.

@szhernovoy
Last active January 28, 2023 23:28
Show Gist options
  • Save szhernovoy/276e69eb90a0de84dd90 to your computer and use it in GitHub Desktop.
Save szhernovoy/276e69eb90a0de84dd90 to your computer and use it in GitHub Desktop.
Simple random strings generator on Swift
func randomString(len:Int) -> String {
let charSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var c = Array(charSet)
var s:String = ""
for n in (1...10) {
s.append(c[Int(arc4random()) % c.count])
}
return s
}
@sokol8
Copy link

sokol8 commented Jan 28, 2023

converting to Array provides 2x performance improvement when generating long strings

e.g. On my Mac (MacBook Pro (16-inch, 2019) 2.3 GHz 8-Core Intel Core i9)
1M random character string generation takes on Average (10 attempts)

  • 2 seconds with String based generation
  • 1 second with Array based generation

Probably it has to do with the following Complexity note
Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the length of the collection.
in https://developer.apple.com/documentation/swift/array/randomelement()

public func randomString(of length: Int) -> String {
    let letters = Array("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
    var s = ""
    for _ in 0 ..< length {
        s.append(letters.randomElement()!)
    }
    return s
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment