Generics Flashcards
What is Monomorphization
The process of turning generic code into specific code by filling in the concrete types that are used when compiled
A Good Example of Monomorphization use case
on Monomorphizing Hashmap Rust is able to create a seperate hashing function for each type so its more optimized.
Downside of Monomorphization
- The downsides is that your binary ends up being larger because u need to generate a copy of the type or the function for every type that is used with.
- the code can be little less efficient because if u have 2 different functions making the computer have to jump to different seperate regions of memory
- could be expensive if u generate ridiciolus amount of types
What is a Static Dispatch
Static dispatch is when the concrete implementation of a method is determined at compile time
Advantages of Static Dispatch
Maximum performance
No runtime overhead
Enables inline optimizations
Type checking at compile time
Disadvantages of Static Dispatch
Increases binary size (code bloat)
Can’t handle cases where types are only known at runtime
All possible types must be available at compile time
When to use Static Dispatch
- Perfomance is critical
- Types are known at compile time
- Working with generic code
When to use Dynamic Dispatch
- Runtime Flexibility
- Hetergonus Collections meaning that the collection has different types
- if u want to use external Code
Why do u need to know size at compile time
it needs to know how much to allocate stack memory for the variables, to generate efficient the compiler must know the size
how to layout the structs in the memory
Track ownership and lifetime
example of things that doens’t have any size on compile time if u make as argument for a functions
str,
[u8]
what is a Vtable
virtual table is a little data structure that has a pointer to each methods for the trait for the type
What is a Fat pointer
a pointer that contains more than 1 pointer
Generic Types Vs Associated Types
Generic Types vs Associated Types:
Generic types (like trait Drive<T>) allow multiple implementations of the same trait for a single type, each with different type parameters.</T>
Associated types (like trait Drive { type DriveType; }) restrict you to only one implementation per type, as you can only specify one associated type per implementation.