gpt4 book ai didi

java - Kotlin/Java 是否使用缓存系统来提高迭代数组时的性能?

转载 作者:行者123 更新时间:2023-12-04 23:58:28 26 4
gpt4 key购买 nike

我的意思是,这样更快吗:

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

比这个:

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

还是完全一样?

我知道这是微优化,但对于复杂的网格(在 openGL 中)它可能会产生影响。

最佳答案

这里是用 Kotlin 编写的基准测试。

<表类="s-表"><头>数组中的项目数测试次数迭代访问随机访问<正文>100_0001000.02 毫秒0.12 毫秒1_000_0001006.15 毫秒74.26 毫秒5_000_00010033.36 毫秒526.46 毫秒
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
}

}

关于java - Kotlin/Java 是否使用缓存系统来提高迭代数组时的性能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72446138/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com