Skip to content

Commit

Permalink
collections: Move optimized String::from_str to String::from
Browse files Browse the repository at this point in the history
This implementation is currently about 3-4 times faster than using
the `.to_string()` based approach.
  • Loading branch information
erickt committed Apr 19, 2015
1 parent 00978a9 commit f055054
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
13 changes: 12 additions & 1 deletion src/libcollections/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)");
}
}

Expand Down
27 changes: 27 additions & 0 deletions src/libcollectionstest/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
})
}

0 comments on commit f055054

Please sign in to comment.