Skip to content

Instantly share code, notes, and snippets.

@tesaguri
Last active July 9, 2017 02:26
Show Gist options
  • Save tesaguri/b03475216d2b2b800c493bea3e2e83ff to your computer and use it in GitHub Desktop.
Save tesaguri/b03475216d2b2b800c493bea3e2e83ff to your computer and use it in GitHub Desktop.
Benchmark test: Box<str> vs String
#![feature(test)]
extern crate test;
use std::collections::HashMap;
use test::Bencher;
const KEY0: &str = "A benchmark test";
const KEY1: &str = "for";
const KEY2: &str = "`Box<str>` and `String`";
const KEY3: &str = "as keys";
const KEY4: &str = "of a map.";
const KEY5: &str = "A long key. Long long long LONG key. Blah blah long blah key blah bench blah blah";
#[bench]
fn boxed_str(b: &mut Bencher) {
let mut map = HashMap::new();
b.iter(|| {
map.insert(KEY0.to_owned().into_boxed_str(), 0);
map.insert(KEY1.to_owned().into_boxed_str(), 1);
map.insert(KEY2.to_owned().into_boxed_str(), 2);
map.insert(KEY3.to_owned().into_boxed_str(), 3);
map.insert(KEY4.to_owned().into_boxed_str(), 4);
map.insert(KEY5.to_owned().into_boxed_str(), 5);
});
}
#[bench]
fn string(b: &mut Bencher) {
let mut map = HashMap::new();
b.iter(|| {
map.insert(KEY0.to_owned(), 0);
map.insert(KEY1.to_owned(), 1);
map.insert(KEY2.to_owned(), 2);
map.insert(KEY3.to_owned(), 3);
map.insert(KEY4.to_owned(), 4);
map.insert(KEY5.to_owned(), 5);
});
}
// running 2 tests
// test boxed_str ... bench: 546 ns/iter (+/- 22)
// test string ... bench: 569 ns/iter (+/- 47)
//
// test result: ok. 0 passed; 0 failed; 0 ignored; 2 measured; 0 filtered out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment