i } }) } fun startFor() { println("For Time: " + measureNanoTime { for (i in 0..(list.size-1)) { list[i] } }) } fun startForUntil() { println("ForUntil Time: " + measureNanoTime { for (i in 0 until list.size) { list[i] } }) } fun startForIn() { println("ForIn Time: " + measureNanoTime { for (i in list.indices) { list[i] } }) } fun startForEach() { println("forEach Time: " + measureNanoTime { list.forEach { i -> i } }) } fun startForEachIndexed() { println("forEachIndexed Time: " + measureNanoTime { list.forEachIndexed {"> i } }) } fun startFor() { println("For Time: " + measureNanoTime { for (i in 0..(list.size-1)) { list[i] } }) } fun startForUntil() { println("ForUntil Time: " + measureNanoTime { for (i in 0 until list.size) { list[i] } }) } fun startForIn() { println("ForIn Time: " + measureNanoTime { for (i in list.indices) { list[i] } }) } fun startForEach() { println("forEach Time: " + measureNanoTime { list.forEach { i -> i } }) } fun startForEachIndexed() { println("forEachIndexed Time: " + measureNanoTime { list.forEachIndexed {"> i } }) } fun startFor() { println("For Time: " + measureNanoTime { for (i in 0..(list.size-1)) { list[i] } }) } fun startForUntil() { println("ForUntil Time: " + measureNanoTime { for (i in 0 until list.size) { list[i] } }) } fun startForIn() { println("ForIn Time: " + measureNanoTime { for (i in list.indices) { list[i] } }) } fun startForEach() { println("forEach Time: " + measureNanoTime { list.forEach { i -> i } }) } fun startForEachIndexed() { println("forEachIndexed Time: " + measureNanoTime { list.forEachIndexed {">
import kotlin.system.measureNanoTime
/**
* You can edit, run, and share this code.
* play.kotlinlang.org
*/
val list = (1..100000).toList()
fun main() {
startMap()
startFor()
startForUntil()
startForIn()
startForEach()
startForEachIndexed()
startWhile()
}
fun startMap() {
println("Map Time: " + measureNanoTime {
list.map { i ->
i
}
})
}
fun startFor() {
println("For Time: " + measureNanoTime {
for (i in 0..(list.size-1)) { list[i] }
})
}
fun startForUntil() {
println("ForUntil Time: " + measureNanoTime {
for (i in 0 until list.size) { list[i] }
})
}
fun startForIn() {
println("ForIn Time: " + measureNanoTime {
for (i in list.indices) { list[i] }
})
}
fun startForEach() {
println("forEach Time: " + measureNanoTime {
list.forEach { i -> i }
})
}
fun startForEachIndexed() {
println("forEachIndexed Time: " + measureNanoTime {
list.forEachIndexed { index, i -> i }
})
}
fun startWhile() {
var i = 0
println("while Time: " + measureNanoTime {
while(i<list.size) {
i++
}
})
}
⭐️ 결과
Map Time: 15900184 For Time: 348984 ForUntil Time: 3145461 ForIn Time: 3620592 forEach Time: 6414756 forEachIndexed Time: 7196908 while Time: 7073345
💙 결과적으로 for문이 가장 빨라 많은 데이터를 처리해야할때는 for문을 사용하자!