faster validate_id
This commit is contained in:
@@ -0,0 +1,78 @@
|
||||
use std::hint::black_box;
|
||||
use criterion::{criterion_group, criterion_main, Criterion};
|
||||
|
||||
fn validate_id_current(id: &str) -> bool {
|
||||
id.len() == 24 && id.chars().all(|c| c.is_ascii_alphanumeric())
|
||||
}
|
||||
|
||||
fn validate_id_improved(id: &str) -> bool {
|
||||
id.len() == 24 && id.bytes().all(|b| b.is_ascii_alphanumeric())
|
||||
}
|
||||
|
||||
fn validate_id_strict(id: &str) -> bool {
|
||||
id.len() == 24
|
||||
&& id
|
||||
.bytes()
|
||||
.all(|b| matches!(b, b'A'..=b'Z' | b'0'..=b'9'))
|
||||
}
|
||||
|
||||
fn sanity_checks() {
|
||||
let valid_upper = "A1B2C3D4E5F6G7H8I9J0K1L2";
|
||||
let valid_lower = "a1b2c3d4e5f6g7h8i9j0k1l2";
|
||||
let invalid_symbol = "A1B2C3D4E5F6G7H8I9J0K1L_";
|
||||
let invalid_len_23 = "A1B2C3D4E5F6G7H8I9J0K1L";
|
||||
let invalid_len_25 = "A1B2C3D4E5F6G7H8I9J0K1L2M";
|
||||
|
||||
assert_eq!(valid_upper.len(), 24);
|
||||
assert_eq!(valid_lower.len(), 24);
|
||||
assert_eq!(invalid_symbol.len(), 24);
|
||||
assert_eq!(invalid_len_23.len(), 23);
|
||||
assert_eq!(invalid_len_25.len(), 25);
|
||||
|
||||
// Текущая версия
|
||||
assert!(validate_id_current(valid_upper));
|
||||
assert!(validate_id_current(valid_lower));
|
||||
assert!(!validate_id_current(invalid_symbol));
|
||||
assert!(!validate_id_current(invalid_len_23));
|
||||
assert!(!validate_id_current(invalid_len_25));
|
||||
|
||||
// Улучшенная версия должна вести себя так же
|
||||
assert!(validate_id_improved(valid_upper));
|
||||
assert!(validate_id_improved(valid_lower));
|
||||
assert!(!validate_id_improved(invalid_symbol));
|
||||
assert!(!validate_id_improved(invalid_len_23));
|
||||
assert!(!validate_id_improved(invalid_len_25));
|
||||
}
|
||||
|
||||
fn bench_validate_id(c: &mut Criterion) {
|
||||
sanity_checks();
|
||||
|
||||
let cases = [
|
||||
("valid_upper", "A1B2C3D4E5F6G7H8I9J0K1L2"),
|
||||
("valid_lower", "a1b2c3d4e5f6g7h8i9j0k1l2"),
|
||||
("invalid_symbol", "A1B2C3D4E5F6G7H8I9J0K1L_"),
|
||||
("invalid_len_23", "A1B2C3D4E5F6G7H8I9J0K1L"),
|
||||
("invalid_len_25", "A1B2C3D4E5F6G7H8I9J0K1L2M"),
|
||||
];
|
||||
|
||||
let mut group = c.benchmark_group("validate_id");
|
||||
|
||||
for (name, input) in cases {
|
||||
group.bench_function(format!("current/{name}"), |b| {
|
||||
b.iter(|| validate_id_current(black_box(input)))
|
||||
});
|
||||
|
||||
group.bench_function(format!("improved/{name}"), |b| {
|
||||
b.iter(|| validate_id_improved(black_box(input)))
|
||||
});
|
||||
|
||||
group.bench_function(format!("strict/{name}"), |b| {
|
||||
b.iter(|| validate_id_strict(black_box(input)))
|
||||
});
|
||||
}
|
||||
|
||||
group.finish();
|
||||
}
|
||||
|
||||
criterion_group!(benches, bench_validate_id);
|
||||
criterion_main!(benches);
|
||||
Reference in New Issue
Block a user