Tuesday, August 27, 2024

My journey of learning Rust - Static dispatch vs Dynamic dispatch...

 In Rust, the Static dispatch means the compiler determines which method to call at compile time. This is in contrast to Dynamic dispatch in which the decision is made during runtime. Static dispatch is the default behaviour in Rust. Static dispatch is used with generics and trait bounds without using the keyword dyn.

Static dispatch is usually faster than dynamic dispatch because there is no need for a runtime lookup in the VTble of the method to be called.

Example of Static Dispatch and Dynamic Dispatch

Please have a look at the below code which has used both Static dispatch as well as Dynamic Dispatch.

trait Animal {
fn make_sound(&self);
fn wag_tail(&self){

println!("i don't have a tail..."); //default behavior
}
}

struct Human;

impl Animal for Human {
fn make_sound(&self) {
println!("Human is speaking...");
}
}

struct Dog;

impl Animal for Dog {

fn make_sound(&self) {
println!("Dog barks...");
}

fn wag_tail(&self) {
println!("The dog is waging it's tail");
}
}

fn static_dispatch_makesound<T : Animal> (animal:T){
animal.make_sound();
}

fn dynamic_dispatch_makesound(animal : &dyn Animal) {
animal.make_sound()
}

fn static_dispatch_wagtail<T : Animal> (animal:T){
animal.wag_tail();
}

fn dynamic_dispatch_wagtail(animal : &dyn Animal) {
animal.wag_tail();
}

fn main() {

let dog = Dog;
let human = Human;

dynamic_dispatch_wagtail(&dog);
static_dispatch_makesound(dog);

dynamic_dispatch_makesound(&human);
static_dispatch_wagtail(human);
}

Please note how static_dispatch has used trait bound function 

fn static_dispatch_makesound<T : Animal> (animal:T){
animal.make_sound();
}

and dynamic dispatch has used the keyword dyn.

fn dynamic_dispatch_wagtail(animal : &dyn Animal){ animal.wag_tail();

Static dispatch is fast and allows function calls to be inlined, which is key for optimization. 

However, Static dispatch can lead to "code bloat" because the binary contains multiple copies of the same function, one for each type.

No comments: