@@ -2,23 +2,23 @@ use criterion::{black_box, criterion_group, criterion_main, Criterion};
22use std:: time:: Duration ;
33
44trait DoSomething {
5- fn do_it ( & self ) -> i32 ;
5+ fn do_it ( & self , i : i32 ) -> i32 ;
66}
77
88struct ActionOne ;
99struct ActionTwo ;
1010
1111impl DoSomething for ActionOne {
1212 #[ inline]
13- fn do_it ( & self ) -> i32 {
14- ( 1 .. 10 ) . fold ( 0 , |acc , x| acc + x )
13+ fn do_it ( & self , i : i32 ) -> i32 {
14+ i + i
1515 }
1616}
1717
1818impl DoSomething for ActionTwo {
1919 #[ inline]
20- fn do_it ( & self ) -> i32 {
21- ( 1 .. 10 ) . map ( |x| x * x ) . sum :: < i32 > ( )
20+ fn do_it ( & self , i : i32 ) -> i32 {
21+ i * i
2222 }
2323}
2424
@@ -27,41 +27,43 @@ enum Action {
2727 Two ( ActionTwo ) ,
2828}
2929
30- fn dynamic_dispatch ( ) -> i32 {
31- let actions: Vec < Box < dyn DoSomething > > = vec ! [ Box :: new( ActionOne ) , Box :: new( ActionTwo ) ] ;
30+ fn dynamic_dispatch ( actions : & Vec < Box < dyn DoSomething > > ) -> i32 {
3231 let mut output = 0 ;
3332 for action in actions {
34- output = output + action. do_it ( ) ;
33+ output = output + action. do_it ( output ) ;
3534 }
3635 output
3736}
3837
39- fn pattern_matching ( ) -> i32 {
40- let actions = vec ! [ Action :: One ( ActionOne ) , Action :: Two ( ActionTwo ) ] ;
38+ fn pattern_matching ( actions : & Vec < Action > ) -> i32 {
4139 let mut output = 0 ;
4240 for action in actions {
4341 match action {
44- Action :: One ( a) => output = output + a. do_it ( ) ,
45- Action :: Two ( a) => output = output + a. do_it ( ) ,
42+ Action :: One ( a) => output = output + a. do_it ( output ) ,
43+ Action :: Two ( a) => output = output + a. do_it ( output ) ,
4644 }
4745 }
4846 output
4947}
5048
5149fn benchmark ( c : & mut Criterion ) {
5250 let mut group = c. benchmark_group ( "Dispatch vs Matching" ) ;
53- group. measurement_time ( Duration :: new ( 10 , 0 ) ) ; // Adjust the measurement time as needed
51+
52+ let dynamic_actions: Vec < Box < dyn DoSomething > > = vec ! [ Box :: new( ActionOne ) , Box :: new( ActionTwo ) ] ;
53+ let static_actions: Vec < Action > = vec ! [ Action :: One ( ActionOne ) , Action :: Two ( ActionTwo ) ] ;
54+
55+ group. measurement_time ( Duration :: new ( 10 , 0 ) ) ;
5456
5557 group. bench_function ( "Dynamic Dispatch" , |b| {
5658 b. iter ( || {
57- let output = dynamic_dispatch ( ) ;
59+ let output = dynamic_dispatch ( & dynamic_actions ) ;
5860 black_box ( output)
5961 } )
6062 } ) ;
61-
63+
6264 group. bench_function ( "Pattern Matching" , |b| {
6365 b. iter ( || {
64- let output = pattern_matching ( ) ;
66+ let output = pattern_matching ( & static_actions ) ;
6567 black_box ( output)
6668 } )
6769 } ) ;
0 commit comments