Ji Sungbin
01/22/2023, 8:27 AMnext()next()Ji Sungbin
01/22/2023, 8:28 AMsuspend fun main() = coroutineScope {
    val times = List(/*100_000*/ 2_000_000_000) {} as ArrayList<Unit>
    val decimal = DecimalFormat("#,###")
    launch {
        var average = 0L
        launch {
            repeat(10) { fastCount ->
                launch(<http://Dispatchers.IO|Dispatchers.IO>) {
                    average += measureNanoTime {
                        var value = 0
                        times.fastForEach {
                            value++
                        }
                    }.also { result ->
                        println("[$fastCount] Collections Fast API: ${result}ns")
                    }
                }
            }
        }.join()
        println("[AVERAGE] Collections Fast API: ${decimal.format(average / 10)}ns")
    }
    launch {
        var average = 0L
        launch {
            repeat(10) { normalCount ->
                launch(<http://Dispatchers.IO|Dispatchers.IO>) {
                    average += measureNanoTime {
                        var value = 0
                        times.forEach {
                            value++
                        }
                    }.also { result ->
                        println("[$normalCount] Collections Normal API: ${result}ns")
                    }
                }
            }
        }.join()
        println("[AVERAGE] Collections Normal API: ${decimal.format(average / 10)}ns")
    }
    Unit
}
@Suppress("BanInlineOptIn")
@OptIn(ExperimentalContracts::class)
inline fun <T> List<T>.fastForEach(action: (T) -> Unit) {
    contract { callsInPlace(action) }
    for (index in indices) {
        val item = get(index)
        action(item)
    }
}ephemient
01/22/2023, 6:06 PMephemient
01/22/2023, 6:09 PMJi Sungbin
01/22/2023, 6:11 PMJi Sungbin
01/22/2023, 6:13 PMephemient
01/22/2023, 6:14 PMDecimalFormatJi Sungbin
01/22/2023, 6:18 PMephemient
01/22/2023, 6:20 PMephemient
01/22/2023, 6:21 PMList.iterator()List.get()ephemient
01/22/2023, 6:22 PMJi Sungbin
01/22/2023, 6:35 PM