You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
We were curious to see why pattern matching was significantly faster compared to dynamic dispatch, so we posted benchmarks on [Reddit](https://www.reddit.com/r/rust/comments/1cx7qvi/performance_pattern_matching_vs_dynamic_dispatch/). We received interesting feedback about the benchmark setup, such as the unnecessary heap allocation for dynamic dispatch. After addressing this, the performance difference was marginal.
39
+
40
+
Digging deeper, especially after this [GitHub comment](https://github.com/tailcallhq/rust-benchmarks/issues/2) and further analysis on [Rust Compiler Explorer](https://rust.godbolt.org/), we discovered that the compiler optimizes the generated machine code based on the seed value set in the variable `output`. When set to `0`, the additions and multiplications would always return `0` regardless of the contents of the passed array. This optimization resulted in the pattern matching case reducing to (an optimization that was unavailable to the `dyn` implementation):
41
+
42
+
```asm
43
+
xor eax, eax
44
+
ret
45
+
```
46
+
47
+
After correcting this by setting the seed value to `1`, the benchmarks showed a significant improvement, making pattern matching only **2.7x faster** than dynamic dispatch.
0 commit comments