Why is a rust executable smaller than Kotlin-native?


#21

Kotlin/native is a magnitude slower than Rust according to the completely unscientific benchmark


#22

The Rust FAQ has some information on binary size as well. (I’m also trying to update the FAQ to reflect the latest information).


#23

Step 7:

Add panic = 'abort' to Cargo.toml. This will remove unwinding landing pads that are needed to support for unwinding panics.


#24

Minimize Size on Stable Rust (>=1.28.0)

Modify main.rs to remove jemalloc allocator and use the system allocator instead:

use std::alloc::System;

#[global_allocator]
static A: System = System;

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

Create a Cargo.toml with:

# The release profile, used for `cargo build --release`.
[profile.release]
opt-level = 'z'  # Optimize for size.
lto = true       # Enable Link Time Optimization
panic = 'abort'  # Abort on panic

Build with the following command:

$ cargo build --release

Strip the build executable (if not on Windows):

$ strip target/release/hello_world

This brings the stripped executable down to 153K on 64-bit macOS.

Going Even Further With Nightly and Xargo

Use Xargo to build the Rust stdlib from source when you build the application, which allows you apply lto and opt-level to the stdlib build, stripping out lots of the stdlib you don’t need.

Modify main.rs:

// Xargo must use a different way to disable jemalloc.
//use std::alloc::System;
//
//#[global_allocator]
//static A: System = System;

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

Add a Xargo.toml file to the root of your project (this doesn’t replace Cargo.toml, just is in addition):

# Xargo.toml
[dependencies.std]
features = ["force_alloc_system"] # Disable jemalloc the Xargo way.
$ rustup default nightly
$ rustup component add rust-src
$ cargo install xargo
# Find your host's target triple.
$ rustc -vV
...
host: x86_64-apple-darwin

# Use that target triple when building with Xargo.
$ xargo build --target x86_64-apple-darwin --release

On my machine, that dropped the stripped "Hello World" executable size on 64-bit macOS to 82KB :fireworks: