wee_alloc - Hello wasm-pack! (original) (raw)

  1. 1. Introduction
  2. 2. Quickstart
  3. 3. Prerequisites
    1. 3.1. npm (optional)
    2. 3.2. considerations
    3. 3.3. Non-rustup setups
  4. 4. Commands
    1. 4.1. new
    2. 4.2. build
    3. 4.3. test
    4. 4.4. pack and publish
    5. 4.5. init (DEPRECATED)
  5. 5. Tutorials
    1. 5.1. Hybrid applications with Webpack
      1. 5.1.1. Getting started
        1. 5.1.2. Using your library
    2. 5.2. npm browser packages
      1. 5.2.1. Getting started
          1. 5.2.1.1. Manual Setup
        1. 5.2.2. Template deep dive
          1. 5.2.2.1. Cargo.toml
            1. 5.2.2.2. src/lib.rs
            2. 5.2.2.3. src/utils.rs
            3. 5.2.2.4. wee_alloc
            4. 5.2.2.5. tests/web.rs
        2. 5.2.3. Building your project
        3. 5.2.4. Testing your project
        4. 5.2.5. Packaging and publishing
        5. 5.2.6. Using your library
  6. 6. Cargo.toml Configuration
  7. 7. Contributing

Hello wasm-pack!

wee_alloc

  1. What is wee_alloc?
  2. Enabling wee_alloc What is wee_alloc?

WebAssembly code is frequently transmitted over the wire to users, so compiled code size is often important to ensure an application loads quickly and is responsive.

wee_alloc is a tiny allocator designed for WebAssembly that has a (pre-compression) code-size footprint of only a single kilobyte.

An analysis suggests that over half of the bare minimum WebAssembly memory footprint is required by Rust's default memory allocator. Yet, WebAssembly code often does not require a sophisticated allocator, since it often just requests a couple of large initial allocations.

wee_alloc trades off size for speed. It has a tiny code-size footprint, but it is not competitive in terms of performance with the default global allocator, for example.

For even more details, see the wee_allocrepository, orgeneral documentation about shrinking code size of WebAssembly binaries.

Enabling wee_alloc

In lib.rs, we have the configuration for wee_alloc inside a cfg_if! macro:


# #![allow(unused_variables)]
#fn main() {
cfg_if! {
    if #[cfg(feature = "wee_alloc")] {
        #[global_allocator]
        static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
    }
}
#}

This code block is intended to initialize wee_alloc as the global memory allocator, but only if the wee_alloc feature is enabled at compile time. The feature can be enabled by passing extra options while building:

$ wasm-pack build --features wee_alloc

or alternatively you could turn it on by default in Cargo.toml:

[features]
default = ["console_error_panic_hook", "wee_alloc"]