Skip to content

Instantly share code, notes, and snippets.

@nihsmik
Created December 28, 2020 09:30
Show Gist options
  • Save nihsmik/01b9996a4953e6f02b295833ca98d47c to your computer and use it in GitHub Desktop.
Save nihsmik/01b9996a4953e6f02b295833ca98d47c to your computer and use it in GitHub Desktop.
Iterable<T>.map vs Iterable<T>.forEach
import kotlin.time.Duration
import kotlin.time.measureTime
fun main() {
val mapResults = mutableListOf<Duration>()
val forEachResults = mutableListOf<Duration>()
repeat(10) {
mapResults.add(measureTime { (0..1_000_000).map { it + 1 } })
forEachResults.add(measureTime { (0..1_000_000).forEach { it + 1 } })
}
println(mapResults)
// [61.9ms, 81.5ms, 55.6ms, 15.5ms, 56.9ms, 18.6ms, 81.2ms, 80.9ms, 52.1ms, 11.5ms]
println(forEachResults)
// [7.09ms, 332us, 491us, 546us, 331us, 372us, 548us, 470us, 326us, 518us]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment