Description
Description:
The match
statement in the provided Rust code generates a jump table with -O3
optimizations, despite the fact that the discriminant values for the enum variants have a fixed offset from their target characters. This results in suboptimal code generation when a more efficient approach is possible.
Reproduction:
use std::fmt::{Display, Formatter};
#[derive(Copy, Clone)]
enum Letter {
A,
B,
C,
}
impl Display for Letter {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let letter = match self {
Letter::A => 'a',
Letter::B => 'b',
Letter::C => 'c',
};
write!(f, "{}", letter)
}
}
Expected Behavior:
Since each discriminant value of the Letter
enum is exactly 97 units away from the corresponding target characters in the match
statement, the compiler should ideally optimize this code to use a direct calculation rather than generating a jump table.
Example of Hand-Optimized Code:
use std::fmt::{Display, Formatter};
#[derive(Copy, Clone)]
enum Letter {
A,
B,
C,
}
impl Display for Letter {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let letter = ((*self as u8) + 97) as char;
write!(f, "{}", letter)
}
}
Compiler Explorer Links:
- Original Code with Suboptimal Optimization: View on Compiler Explorer
- Hand-Optimized Code: View on Compiler Explorer
Additional Notes:
Although manual optimization achieves the desired performance, automatic optimization by the compiler is preferred to ensure both efficiency and maintainability of the code.