Last active
August 6, 2020 22:18
-
-
Save indiv0/539453c2cac132f969162917f09a5776 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[inline] | |
fn is_hex_prefixed_matches(s: &str) -> bool { | |
matches!(s.as_bytes(), [b'0',b'x', ..] | [b'0',b'X', ..]) | |
} | |
#[inline] | |
fn is_hex_prefixed_unsafe(s: &str) -> bool { | |
let x = | |
unsafe { ((*s.as_ptr() as u16) << 8) | (*s.as_ptr().add((s.len() > 1) as usize)) as u16 }; | |
(x ^ 0x3078) & (x ^ 0x3050) == 0 | |
} | |
#[inline] | |
pub fn is_hex_prefixed_checked(s: &str) -> bool { | |
let bytes = s.as_bytes(); | |
if bytes.len() >= 2 { | |
let array = unsafe{ *(bytes.as_ptr() as *const [u8;2]) }; | |
matches!(&array, b"0x" | b"0X") | |
}else{ | |
false | |
} | |
} | |
use criterion::{black_box, criterion_group, criterion_main, Criterion}; | |
use rand::Rng; | |
use rand::rngs::ThreadRng; | |
pub fn criterion_benchmark(c: &mut Criterion) { | |
let mut rng = rand::thread_rng(); | |
const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\ | |
abcdefghijklmnopqrstuvwxyz\ | |
0123456789)(*&^%$#@!~"; | |
const STR_LEN: usize = 8; | |
fn rand_str(rng: &mut ThreadRng) -> String { | |
(0..STR_LEN).map(|_| { | |
let idx = rng.gen_range(0, CHARSET.len()); | |
CHARSET[idx] as char | |
}) | |
.collect() | |
} | |
let rand_strs: Vec<String> = (0..1000000).map(|_| rand_str(&mut rng)).collect(); | |
let mut iter_1 = rand_strs.iter().cycle(); | |
let mut iter_2 = rand_strs.iter().cycle(); | |
let mut iter_3 = rand_strs.iter().cycle(); | |
c.bench_function("is_hex_prefixed_matches", |b| b.iter(|| is_hex_prefixed_matches(black_box(iter_1.next().unwrap())))); | |
c.bench_function("is_hex_prefixed_unsafe", |b| b.iter(|| is_hex_prefixed_unsafe(black_box(iter_2.next().unwrap())))); | |
c.bench_function("is_hex_prefixed_checked", |b| b.iter(|| is_hex_prefixed_checked(black_box(iter_3.next().unwrap())))); | |
} | |
criterion_group!(benches, criterion_benchmark); | |
criterion_main!(benches); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment