Monomorphization

Source: Wikipedia, the free encyclopedia.

In

polymorphic functions are replaced by many monomorphic functions for each unique instantiation.[1] It is considered beneficial to undergo the mentioned transformation because it results in the output intermediate representation (IR) having specific types, which allows for more effective optimization. Additionally, many IRs are intended to be low-level and do not accommodate polymorphism. The resulting code is generally faster than dynamic dispatch, but may require more compilation time and storage space due to duplicating the function body.[2][3][4][5][6][7]

Example

This is an example of a use of a generic identity function in Rust

fn id<T>(x: T) -> T {
    return x;
}

fn main() {
    let int = id(10);
    let string = id("some text");
    println!("{int}, {string}");
}

After monomorphization, this would become equivalent to

fn id_i32(x: i32) -> i32 {
    return x;
}

fn id_str(x: &str) -> &str {
    return x;
}

fn main() {
    let int = id_i32(10);
    let string = id_str("some text");
    println!("{int}, {string}");
}

See also

References

  1. ^ "Generic Data Types - The Rust Programming Language". Retrieved 27 May 2021.
  2. ^ Hume, Tristan. "Models of Generics and Metaprogramming: Go, Rust, Swift, D and More". Retrieved 27 May 2021.
  3. .
  4. CiteSeerX 10.1.1.663.6849. {{cite journal}}: Cite journal requires |journal= (help
    )
  5. .
  6. .
  7. .