Optimize a Rust program

Compiling Rust programs to WebAssembly often increases the file size of the program significantly. The DFINITY Rust CDK includes a helper library—ic-cdk-optimizer—that you can use to reduce the size of Rust-based canisters before deploying them on the Internet Computer.

Before you begin

Before you optimize your program, verify the following:

  • You have an internet connection and access to a shell terminal on your local macOS or Linux computer.

  • You have downloaded and installed the Rust programming language and Cargo as described in the Rust installation instructions for your operating system.

    curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh

    The Rust tool chain must be at version 1.46.0, or later.

  • You have downloaded and installed the DFINITY Canister Software Development Kit (SDK) package as described in Download and install.

  • You have cmake installed. For example, use Homebrew with the following command:

    brew install cmake

    For instructions on how to install Homebrew, see the Homebrew Documentation.

  • You have successfully compiled your program to a WebAssembly module (WASM) and deployed it on the Internet Computer running locally.

Install and run the optimizer

To optimize a canister that resulted from compiling a Rust program:

  1. Check that you are still in root directory for your project directory, if needed.

  2. Install the ic-cdk-optimizer crate, if you have not previously installed it, by running the following command:

    cargo install ic-cdk-optimizer

    This package optimizes your Rust code to reduce the size of the WebAssembly output to ensure your program can be uploaded to the Internet Computer network as a canister.

  3. Create a release directory within the src directory for your program by running a command similar to the following:

    mkdir -p src/rust-canister/target/wasm32-unknown-unknown/release/
  4. Optimize the code within the target directory by running a command similar to the following:

    ic-cdk-optimizer target/wasm32-unknown-unknown/release/_rust_canister_.wasm -o target/wasm32-unknown-unknown/release/_rust_canister_-opt.wasm