Created
July 22, 2026 18:36
-
-
Save Kobzol/1dbd9b225642a6cb30e9b97df06f595e to your computer and use it in GitHub Desktop.
Benchmarks for escape_default
This file contains hidden or 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
| use std::hint::black_box; | |
| use include_bytes::DATA; | |
| use include_bytes::{escape_string_std, escape_string_manual}; | |
| use criterion::{Criterion, criterion_group, criterion_main}; | |
| fn criterion_benchmark(c: &mut Criterion) { | |
| c.bench_function("stdlib", |b| b.iter(|| black_box(escape_string_std(black_box(DATA))))); | |
| c.bench_function("manual", |b| b.iter(|| black_box(escape_string_manual(black_box(DATA))))); | |
| } | |
| criterion_group!(benches, criterion_benchmark); | |
| criterion_main!(benches); |
This file contains hidden or 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
| let byte_count = 30usize * 1024 * 1024; | |
| let string_data: String = ('a'..'z').cycle().take(byte_count).collect(); | |
| std::fs::write("blob.txt", string_data).expect("cannot write string blob"); |
This file contains hidden or 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
| #![feature(iter_collect_into)] | |
| use std::fmt::Write; | |
| pub const DATA: &str = include_str!("../blob.txt"); | |
| pub fn escape_string_std(s: &str) -> String { | |
| let mut ret = String::with_capacity(s.len()); | |
| s.escape_default().collect_into(&mut ret); | |
| ret | |
| } | |
| pub fn escape_string_manual(s: &str) -> String { | |
| let mut escaped = String::with_capacity(s.len()); | |
| for c in s.chars() { | |
| match c { | |
| '\t' => escaped.push_str("\\t"), | |
| '\r' => escaped.push_str("\\r"), | |
| '\n' => escaped.push_str("\\n"), | |
| '\\' => escaped.push_str("\\\\"), | |
| '\'' => escaped.push_str("\\'"), | |
| '\"' => escaped.push_str("\\\""), | |
| '\x20'..='\x7e' => escaped.push(c), | |
| c => write!(escaped, "\\u{{{:x}}}", c as u32).unwrap(), | |
| } | |
| } | |
| escaped | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment