【问题标题】:in Kotlin,The second call to joinToString is faster than the first call在 Kotlin 中,第二次调用 joinToString 比第一次调用快
【发布时间】:2021-02-24 22:53:54
【问题描述】:

这是我的代码

fun main() {
val list1 = listOf("channel_name", "timestamp_us", "column_3", "column_4", "channel_name", "timestamp_us", "column_3", "column_4")
val start = System.nanoTime()
list1.joinToString(prefix = "(", postfix = ")")
val end = System.nanoTime()
print(end - start)}

而且产量远远超过 1,000,000。通常在 8,000,000 左右。 但是,如果我将代码更改为:

fun main() {
val list1 = listOf("channel_name", "timestamp_us", "column_3", "column_4", "channel_name", "timestamp_us", "column_3", "column_4")
val list2 = listOf("channel_name", "timestamp_us", "column_3", "column_4", "channel_name", "timestamp_us", "column_3", "column_4")
list1.joinToString()
val start = System.nanoTime()
list2.joinToString(prefix = "(", postfix = ")")
val end = System.nanoTime()
print(end - start)}

输出通常为 15,000。

那么,谁能解释一下为什么第一个代码的输出是第二个代码的 600 倍

我的电脑是 MacBook Pro(16 英寸,2019 年),

jdk 是 jdk1.8.0_251,

在 IntelliJ IDEA 2020.2.2(社区版)中运行的代码

Kotlin 插件版本为 1.4.10

【问题讨论】:

标签: java kotlin


【解决方案1】:

+1 到FedericoklezCulloca,对这么小的案例进行有意义的测试或多或少是不可能的(至少非常困难)。据我所知,由于 JVM “预热”现象,第二个似乎更快,这与 JVM 使用动态编译器有关。

基本上,第二个代码为 JVM 提供了一些时间来实际编译第二个 joinToString(您正在测量的那个)。而在第一个示例中,它可能只是作为解释代码运行。

顺便说一句,这只是一种直觉,在微基准测试中很难指出单一原因。

【讨论】:

    猜你喜欢
    • 2012-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-03
    • 1970-01-01
    相关资源
    最近更新 更多