Auto merge of - erickt:str, r=alexcrichton

This implementation is currently about 3-4 times faster than using the `.to_string()` based approach.

I would also suggest we deprecate `String::from_str` since it's redundant with the stable `String::from` method, but I'll leave that for a future PR.
This commit is contained in:
bors 2015-04-19 19:32:45 +00:00
commit da355efc1c
2 changed files with 39 additions and 1 deletions
src
libcollections
libcollectionstest

@ -1013,9 +1013,20 @@ impl AsRef<str> for String {
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> From<&'a str> for String {
#[cfg(not(test))]
#[inline]
fn from(s: &'a str) -> String {
s.to_string()
String { vec: <[_]>::to_vec(s.as_bytes()) }
}
// HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
// required for this method definition, is not available. Since we don't
// require this method for testing purposes, I'll just stub it
// NB see the slice::hack module in slice.rs for more information
#[inline]
#[cfg(test)]
fn from(_: &str) -> String {
panic!("not available with cfg(test)");
}
}

@ -450,3 +450,30 @@ fn bench_exact_size_shrink_to_fit(b: &mut Bencher) {
r
});
}
#[bench]
fn bench_from_str(b: &mut Bencher) {
let s = "Hello there, the quick brown fox jumped over the lazy dog! \
Lorem ipsum dolor sit amet, consectetur. ";
b.iter(|| {
String::from_str(s)
})
}
#[bench]
fn bench_from(b: &mut Bencher) {
let s = "Hello there, the quick brown fox jumped over the lazy dog! \
Lorem ipsum dolor sit amet, consectetur. ";
b.iter(|| {
String::from(s)
})
}
#[bench]
fn bench_to_string(b: &mut Bencher) {
let s = "Hello there, the quick brown fox jumped over the lazy dog! \
Lorem ipsum dolor sit amet, consectetur. ";
b.iter(|| {
s.to_string()
})
}