Skip to content

Instantly share code, notes, and snippets.

@danieltmbr
Last active September 21, 2017 09:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danieltmbr/1e71c0d3476b0367b60ad77ad7185eb4 to your computer and use it in GitHub Desktop.
Save danieltmbr/1e71c0d3476b0367b60ad77ad7185eb4 to your computer and use it in GitHub Desktop.
Compare performance reduce to joined & map+joined
/**
Measuring the performance of reduce compared to joined and map+joined.
Spoiler: map+joined way more faster!!!
Try this code in a .playground file if you want.
*/
func measure(closure: (()->Void)) {
let start = Date()
closure()
let interval = Date().timeIntervalSince(start)
print(interval)
}
// joined vs. reduce
let nested: [[UInt8]] = Array(repeating: Array(repeating: 200, count: 100), count: 100)
// 0.00224500894546509 sec
measure {
_ = nested.joined()
}
// 1.02885299921036 sec
measure {
_ = nested.reduce([]) { $0 + $1 }
}
// map + joined vs. reduce
let values: [UInt8] = Array(repeating: 200, count: 10000)
// 0.34653902053833 sec
measure {
_ = values.map{"\($0)"}.joined()
}
// 16.6465470194817 sec
measure {
_ = values.reduce("") {
return "\($0)\($1)"
}
}
// map + joined with separator vs. reduce
// 0.499653995037079 sec
measure {
_ = values.map{"\($0)"}.joined(separator: ".")
}
// 22.2956600189209 sec
measure {
_ = values.reduce("") {
return $0 + ($0.isEmpty ? "" : ".") + "\($1)"
}
}
// Results: map+joined burnt reduce
// 0.00224500894546509 vs 1.02885299921036
// 0.34653902053833 vs 16.6465470194817
// 0.499653995037079 vs 22.2956600189209
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment