为什么我的相同索引实现比 Kotlin 提供的更快?

Ely*_*lye 1 kotlin

我正在试验下面的 Kotlin 代码

    fun CharSequence.isMyBlank(): Boolean {
        return indices.all { this[it].isWhitespace() }
    }
Run Code Online (Sandbox Code Playgroud)

如果我测试它的使用效率如何

    @Test
    fun testing() {
        val timeUsed = measureNanoTime {
            repeat(1000) {
                "     ".isMyBlank()
            }
        }
        println(timeUsed)
    }
Run Code Online (Sandbox Code Playgroud)

据报道,使用时间约为 5.6 毫秒。

但是,如果我只是创建自己的indices函数(与 Kotlin 提供的函数相同)

    fun CharSequence.isMyBlank(): Boolean {
        return indices.all { this[it].isWhitespace() }
    }

    public val CharSequence.indices: IntRange
        get() = 0..length - 1
Run Code Online (Sandbox Code Playgroud)

运行上面相同的测试,结果一致为大约 2 毫秒。

我认为我自己的索引和 Kotlin 提供的索引没有什么不同

    public val CharSequence.indices: IntRange
        get() = 0..length - 1
Run Code Online (Sandbox Code Playgroud)

为什么拥有我自己的可以使执行速度更快?

k31*_*159 5

这是因为加载StringsKt.class包含CharSequence.indices. 为了证明这一点,请尝试以下程序:

import kotlin.system.measureNanoTime

fun CharSequence.isMyBlank(): Boolean = indices.all { this[it].isWhitespace() }

fun main() {
    //val ignored = "".indices
    val timeUsed: Long = measureNanoTime {
        repeat(1000) {
            "     ".isMyBlank()
        }
    }
    println(timeUsed / 1e6)
}
Run Code Online (Sandbox Code Playgroud)

测量时间。然后取消注释行,并再次测量。你会发现它运行得更快。以下是我笔记本电脑上的测试结果:

  • 注释掉后val ignored = "".indices12.4 毫秒
  • 就位val ignored = "".indices3.8 毫秒

最大的区别是,当您调用 时"".indices,它会加载该类StringsKt,并且该类现在在开始计时之前已在内存中。

在实际应用程序中,您已经加载了 StringsKt,因此编写您自己的indices.