Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Kotlin/Java use a cache system to improve the performance when iterating arrays?

I mean, is this faster :

myArray[0]++
myArray[1]++
myArray[2]++
...
myArray[1000000000]++

than this :

myArray[864981]++
myArray[526]++
myArray[19347]++
...
myArray[86198116]++

Or is it exactly the same?

I know this is micro optimization, but for complex meshes (in openGL) it might have an impact.

like image 353
Denis Avatar asked Dec 03 '25 04:12

Denis


1 Answers

Here, a benchmark test written in Kotlin.

Number Of Items in Array Test count Iterative Access Random Access
100_000 100 0.02 ms 0.12 ms
1_000_000 100 6.15 ms 74.26 ms
5_000_000 100 33.36 ms 526.46 ms
import kotlin.time.*

fun main(args: Array<String>) {
  val tester = ArrayAccessTest()

    val maxIteration = 100
    val numberOfItems = 1_000_000
    val myArrayForIterate = Array(numberOfItems) { 0 }
    val myArrayForRandom = Array(numberOfItems) { 0 }

  val meanOfIterate = tester.iterate(myArrayForIterate, maxIteration)
  val meanOfRandom = tester.randomAccess(myArrayForRandom, maxIteration)

  println("elapsed mean time for iterative access = $meanOfIterate ms")
  println("elapsed mean time for random access = $meanOfRandom ms")
}

@OptIn(ExperimentalTime::class)
class ArrayAccessTest {

  fun iterate(myArray: Array<Int>, maxIteration: Int): Double {
    val elapsedTimes = mutableListOf<Duration>()

    for (i in 0 until maxIteration) {
      val elapsedTime = measureTime {
        for (index in myArray.indices) {
          myArray[index]++
        }
      }
      elapsedTimes.add(elapsedTime)
    }

    return getMeanOf(elapsedTimes)
  }

  fun randomAccess(myArray: Array<Int>, maxIteration: Int): Double {
    val elapsedTimes = mutableListOf<Duration>()
    val randomIndexes: Array<Int> = myArray.indices.shuffled().toTypedArray()

    for (i in 0 until maxIteration) {
      val elapsedTime = measureTime {
        for (index in randomIndexes) {
          myArray[index]++
        }
      }
      elapsedTimes.add(elapsedTime)
    }

    return getMeanOf(elapsedTimes)
  }

  private fun getMeanOf(elapsedTimes: List<Duration>): Double {
    var total = 0.0
    for (elapsedTime in elapsedTimes) {
      total += elapsedTime.inWholeMilliseconds
    }
    return total / elapsedTimes.size
  }

}
like image 175
ocos Avatar answered Dec 05 '25 20:12

ocos