Last active
April 5, 2016 23:05
-
-
Save h0tk3y/b8fe0da736f69e4c0685b525bbaf3577 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| import kotlin.system.measureTimeMillis | |
| class Matrix<T>(val items: Array<Array<T>>) { | |
| val rows: Int get() = items.size | |
| val cols: Int get() = items.size | |
| operator fun get(i: Int, j: Int): T = items[i][j] | |
| } | |
| data class MutableCell<T>(var i: Int, var j: Int, var value: T) | |
| fun <T> Matrix<T>.withIndexSequence(): Sequence<MutableCell<T>> { | |
| val cell = MutableCell(0, 0, this[0, 0]) | |
| return generateSequence(cell) { cell -> | |
| cell.j += 1 | |
| if (cell.j >= rows) { | |
| cell.j = 0 | |
| cell.i += 1 | |
| if (cell.i >= cols) { | |
| return@generateSequence null | |
| } | |
| } | |
| cell.value = this[cell.i, cell.j] | |
| cell | |
| } | |
| } | |
| inline fun <T> Matrix<T>.forEachIndexed(callback: (Int, Int, T) -> Unit) { | |
| for (i in 0..cols - 1) { | |
| for (j in 0..rows - 1) { | |
| callback(i, j, this[i, j]) | |
| } | |
| } | |
| } | |
| data class Cell<T>(val i: Int, val j: Int, val item: T) | |
| fun <T> Matrix<T>.withIndex() = | |
| (0..rows - 1).flatMap { i -> | |
| (0..cols - 1).map { j -> | |
| Cell(i, j, this[i, j]) | |
| } | |
| } | |
| fun main(args: Array<String>) { | |
| val m = Matrix(Array(400) { Array(400) { String("item".toCharArray()) } }) | |
| val iterations = 1000 | |
| var result = 0 | |
| val seqTime = measureTimeMillis { | |
| repeat(iterations) { | |
| for ((i, j, item) in m.withIndexSequence()) { | |
| result += item.length * i * j | |
| } | |
| } | |
| } | |
| println("seqTime: $seqTime ms") | |
| val callbackTime = measureTimeMillis { | |
| repeat(iterations) { | |
| m.forEachIndexed { i, j, item -> | |
| result += item.length * i * j | |
| } | |
| } | |
| } | |
| println("callbackTime: $callbackTime") | |
| val allocTime = measureTimeMillis { | |
| repeat(iterations) { | |
| for ((i, j, item) in m.withIndex()) { | |
| result += item.length * i * j | |
| } | |
| } | |
| } | |
| println("allocTime: $allocTime ms") | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment