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 17, 2015
1 parent f305579 commit c8841d2
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/libcollections/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1015,7 +1015,7 @@ impl AsRef<str> for String {
impl<'a> From<&'a str> for String {
#[inline]
fn from(s: &'a str) -> String {
s.to_string()
String { vec: <[_]>::to_vec(s.as_bytes()) }
}
}

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 c8841d2

Please sign in to comment.