We studied what characteristics the match statement of Rust has at an assembly level.
-
Enum types
- This statement for those types is basically converted into a branch using the cmp or jmp instruction or a branch based on a jump table, although some processing may be dropped during optimization. We could not find any assembly instructions specific to the match statement.
-
Strings
- We found that specific branch approaches may be applied for strings.
Omitted
For the match instruction containing strings, we found the same characteristics in release builds and size-minimized binaries.
In the assembly for comparison part shown below, the numbers of characters are first compared and then the strings are compared.
We can presume that optimization skips unnecessary string comparison by comparing character counts, which takes less time, before strings.
In general, strings are compared through the cmp instruction or APIs including memcmp() and strcmp(). This binary, however, used an xor instruction to compare strings.
This approach utilizes the characteristics that an xor operation of the same values results in zero.
We can find the same characteristics also in 32-bit binaries.
- Strings
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
return;
}
let input = &args[1];
match input.as_str() {
"apple" => println!("this is an apple."),
"banana" => println!("this is a banana."),
"orange" => println!("this is a orange."),
"grape" => println!("this is a grape."),
"kiwi" => println!("this is a kiwi."),
_ => println!("this is an unknown fruit."),
}
}