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

Time:05-31

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.

CodePudding user response:

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
  }

}
  • Related