Skip to content

Instantly share code, notes, and snippets.

@ljedrz

ljedrz/main.rs Secret

Created October 31, 2018 09:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ljedrz/953a3fb74058806519bd4d640d6f65ae to your computer and use it in GitHub Desktop.
Save ljedrz/953a3fb74058806519bd4d640d6f65ae to your computer and use it in GitHub Desktop.
String::from_utf16 using a pre-allocated push loop vs. collect()
#![feature(test)]
extern crate test;
use test::{Bencher, black_box};
use std::string::FromUtf16Error;
use std::char::decode_utf16;
const S15: &[u16]= &[0xd800, 0xdf45, 0xd800, 0xdf3f, 0xd800, 0xdf3b, 0xd800, 0xdf46, 0xd800,
0xdf39, 0xd800, 0xdf3b, 0xd800, 0xdf30, 0x000a];
const S41: &[u16] = &[0xd801, 0xdc8b, 0xd801, 0xdc98, 0xd801, 0xdc88, 0xd801, 0xdc91, 0xd801,
0xdc9b, 0xd801, 0xdc92, 0x0020, 0xd801, 0xdc95, 0xd801, 0xdc93, 0x0020,
0xd801, 0xdc88, 0xd801, 0xdc9a, 0xd801, 0xdc8d, 0x0020, 0xd801, 0xdc8f,
0xd801, 0xdc9c, 0xd801, 0xdc92, 0xd801, 0xdc96, 0xd801, 0xdc86, 0x0020,
0xd801, 0xdc95, 0xd801, 0xdc86, 0x000a];
fn old(str_u16: &[u16]) -> Result<String, FromUtf16Error> {
String::from_utf16(str_u16)
}
fn new(str_u16: &[u16]) -> Result<String, ()> {
let mut ret = String::with_capacity(str_u16.len());
for c in decode_utf16(str_u16.iter().cloned()) {
if let Ok(c) = c {
ret.push(c);
} else {
return Err(());
}
}
Ok(ret)
}
#[bench]
fn bench_old(b: &mut Bencher) {
b.iter(|| old(black_box(S41)))
}
#[bench]
fn bench_new(b: &mut Bencher) {
b.iter(|| new(black_box(S41)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment