为什么 Kotlin 本机可执行文件比等效的 Rust 可执行文件大?

Why is a Kotlin native executable larger than the equivalent Rust executable?

我创建了 2 个简单的 "Hello World!" 程序,一个使用 Kotlin,一个使用 Rust:

科特林:

fun main() {
    println("Hello, world!")
}

生锈:

fn main() {
    println!("Hello, world!");
}

我为两者生成了可执行文件: kotlinc-native main.kt 用于 Kotlin,cargo build --release 用于 Rust,然后使用 ls -S -lh | awk '{print , }'.

检查二进制大小

我发现 Kotlin native 生成​​的文件大小是 Rust 生成文件的 1.48 倍

为什么会存在这种差异?

$ ./program.kexe
Hello, world!
$ ls -S -lh | awk '{print , }'

835K program.kexe
43B main.kt

$ ./rust
Hello, world!
$ ls -S -lh | awk '{print , }'

565K rust
128B deps
104B rust.d
64B build
64B examples
64B incremental
64B native

而且 Rust 可以优化得更小,Kotlin native 有类似的东西吗?

初始设置:

$ cargo new hello_world

Build with:

$ cargo build

=> 589,004 bytes

优化步骤 1:

Build with:

$ cargo build --release

=> 586,028 bytes

优化步骤 2:

Change contents of  main.rs  to:

 use std::alloc::System;

#[global_allocator]
static A: System = System;

fn main() {
    println!("Hello, world!");
}

=> 335,232 bytes

优化步骤 3:

Add below to Cargo.toml .

[profile.release]
lto = true

=> 253,752 bytes

优化步骤 4:

Strip executable via

$ strip target/release/hello_world

=> 177,608 bytes

因此,我们最终得到 kotlin native 生成​​的文件是 rust 生成的文件的 4.87 倍(~ 5 倍)

Rust 没有垃圾收集器

因为 Kotlin 需要包含 JVM。