Why is a rust executable smaller than Kotlin-native?


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


Edit: The old website has been deprecated, and it was indicated that the FAQ will not be migrated to the new site. See min-sized-rust1 for an alternative.

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


Step 7:

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



I’ve created a small min-sized-rust repository to track this information since the old website with the binary size FAQ is deprecated. Hopefully this repo can be linked to in the future when others have this question.

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;

static A: System = System;

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

Create a Cargo.toml with:

# The release profile, used for `cargo build --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;
//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
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:

bare-metal: Panics can bloat binary. No handling at all possible?
Building for Raspberry from Windows 10