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 a52182f commit d824de1
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
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
29 changes: 28 additions & 1 deletion src/libcollectionstest/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use std::iter::repeat;
use std::str::Utf8Error;
use std::string::as_string;

use test::Bencher;
use test::{self, Bencher};

#[test]
fn test_as_string() {
Expand Down 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(|| {
test::black_box(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(|| {
test::black_box(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(|| {
test::black_box(s.to_string());
})
}

0 comments on commit d824de1

Please sign in to comment.