我try 在敏捷的Kotlin 中对大小为敏捷的000000的数组进行排序,我发现它们之间存在巨大的性能差距.对于这个数字,Kotlin 几乎比敏捷的18倍(在我的机器上).

I recorded some results and i found that swift is faster when the size is around 10000 or less but once the number goes up, 敏捷的 becomes significantly slow as compare to Kotlin .

Code for 敏捷的 and Kotlin is below,

敏捷的

let n = 100000000
var arr = Array(repeating: 0, count: n)

for i in 1...n {
    arr[i-1] = Int(arc4random_uniform(UInt32(n)))
}

//Record time before sort
arr.sort()
//Record time after sort

Kotlin

val n = 100000000
val arr = IntArray(n)

for (i in 1..n) {
    arr[i-1] = Random().nextInt(n)
}

//Record time before sort
arr.sort()
//Record time after sort

记录的时间如下:,

敏捷的

Size: 1000    Time:  0.001 sec
Size: 10000    Time: 0.009 - 0.01 sec
Size: 100000    Time: 0.122 - 0.127 sec
Size: 1000000    Time: 1.392 - 1.409 sec
Size: 10000000    Time: 16.115 - 16.569 sec
Size: 100000000    Time: 187.346 - 187.71 sec

Size: 1000000000    Waited more than 6 minutes and gave up!

Kotlin

Size: 1000    Time: 0.06 sec
Size: 10000    Time: 0.063 - 0.084 sec
Size: 100000    Time: 0.083 - 0.105 sec
Size: 1000000    Time: 0.23 - 0.501 sec
Size: 10000000    Time: 1.098 - 1.807 sec
Size: 100000000    Time: 10.759 - 11.141 sec

Size: 1000000000    Time: 124.252 - 127.54 sec

So, here you can see 敏捷的 is becoming extremely slow when size increases although it is faster when the number is small.

推荐答案

As MartinR highlighted to compile with release build configuration for Swift so i changed it to release and with that it seems Swift is faster for any number as shown in the below results,

Swift with Build Configuration as release

Size: 1000    Time:  0.001 sec
Size: 10000    Time: 0.001 sec
Size: 100000    Time: 0.006 - 0.007 sec
Size: 1000000    Time: 0.076 - 0.081 sec
Size: 10000000    Time: 0.891 - 0.898 sec
Size: 100000000    Time: 9.01 - 10.14 sec

Size: 1000000000    Time: 113.87 - 117.285 sec

这可能有助于人们在release构建配置中判断Swift个结果.在执行某种性能基准测试时,如上图所示,调试和发布配置中的结果差异很大.

In debug and release configurations, compiler uses different optimization levels so it affects the performance. Some discussion on optimization levels can be found in this question

Kotlin相关问答推荐

为什么Kotlin函数参数名会 destruct 方法调用?

Rabin-Karp字符串匹配的实现(Rolling hash)

Kotlin中用于调用常量名称的枚举类方法之间的区别

为什么记得不将 StateFlow 转换为特定类型?

Jetpack Compose:当状态从另一个活动改变时强制重组

如何在 Kotlin 中不受约束?

如何在 jOOQ 中两次加入同一张表?

如何将字符串格式化为电话号码kotlin算法

这是什么 Kotlin 类型:(String..String?)

在 Kotlin 中,当枚举类实现接口时,如何解决继承的声明冲突?

如何创建 Kotlin DSL - DSL 语法 Kotlin

Kotlin 中的 Java Scanner 相当于什么?

kotlin,如何从函数返回类类型

如何在主线程上使用 Kotlin 协程 await()

在Kotlin中传递并使用函数作为构造函数参数

Kotlin val difference getter override vs assignment

如何在Kotlin中获得KType?

Kotlin - 是否可以在类中的 init 块之前初始化伴随对象?

kotlin中的全局可拓函数

将 androidx.constraintlayout:constraintlayout lib 更新到 2.0.2 版本后出现崩溃 isRtl () null 引用