Created
March 11, 2020 13:36
-
-
Save abesmon/10b68305adce0837be23b194da9f9a1f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func randomString(length: Int) -> String { | |
return (0..<length).map { _ in String(Int.random(in: 0...9)) }.joined() | |
} | |
func randomStringBuffer(length: Int) -> String { | |
var buffer = "" | |
(0..<length).forEach { _ in buffer += String(Int.random(in: 0...9)) } | |
return buffer | |
} | |
func randomStringB(length: Int) -> String { | |
let letters = "0123456789" | |
return String((0..<length).map{ _ in letters.randomElement()! }) | |
} | |
func test(_ funcToRun: () -> Void) { | |
let a = Date().timeIntervalSince1970 | |
_ = funcToRun() | |
let b = Date().timeIntervalSince1970 | |
print(b - a) | |
} | |
test { | |
let g = randomString(length: 10000) | |
} | |
test { | |
let f = randomStringBuffer(length: 10000) | |
} | |
test { | |
let g = randomStringB(length: 10000) | |
} | |
/** | |
several test results: | |
0.13645076751708984 | |
0.34798574447631836 | |
0.22037696838378906 | |
0.134080171585083 | |
0.2427217960357666 | |
0.1422710418701172 | |
0.13546204566955566 | |
0.28347301483154297 | |
0.2760488986968994 | |
0.13517093658447266 | |
0.347398042678833 | |
0.197998046875 | |
Seems better approach is to use joined() | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment