rust-lang/rust — pull request #18149 by veddan (2014-10-19 00:19:46+00:00)
Title: Optimize MemWriter::write_char

Previously, the `write_char` function typically made a call to `memcpy` (as seen in `ltrace`) to copy the UTF-8 encoded bytes. For the common ASCII case that meant a lot of 1-byte `memcpy`s. It sometimes got rid of the call in microbenchmarks, but rarely in real code. This commit gets rid of the call to `memcpy`.

For this benchmark (compiled with -O), performance improves a lot:

#![feature(slicing_syntax)]
extern crate test;
use std::io::MemWriter;
use test::Bencher;

#[inline(never)]
fn f(w: &mut W, c: char) {
w.write_char(c);
w.write_char(c);
w.write_char(c);
}

#[bench]
fn bench_write_char(b: &mut Bencher) {
let n = 10000;
let s = String::from_char(n, 'x');
b.iter(|| {
let mut w = MemWriter::with_capacity(3*n + 1);
for c in s[].chars() {
f(&mut w, c);
}
test::black_box(w);
});
b.bytes = 3 * n as u64;
}

Before

test bench_write_char ... bench: 252621 ns/iter (+/- 11388) = 118 MB/s

After

test bench_write_char ... bench: 163071 ns/iter (+/- 5512) = 183 MB/s