Reference articles on history, science, culture and more
Encyclopedia

Monomorphization

Compile-time transformation

In programming languages, monomorphization is a compile-time process where polymorphic functions are replaced by many monomorphic functions for each unique instantiation. 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.

01Example

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}"); }
Watch videos about MonomorphizationExplainers and documentaries on YouTube (opens in a new tab)

Sources and credits

This article is adapted from the Wikipedia article Monomorphization, written by its contributors and licensed under CC BY-SA 4.0. Fathomly has changed the layout, removed citation markers, navigation and maintenance notices, and adjusted punctuation. This adapted version is shared under the same license. For references, see the original article.

Fathomly is not affiliated with or endorsed by the Wikimedia Foundation. Spotted a problem? Tell us.