Skip to content

Commit d824de1

Browse files
committed
collections: Move optimized String::from_str to String::from
This implementation is currently about 3-4 times faster than using the `.to_string()` based approach.
1 parent a52182f commit d824de1

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

src/libcollections/string.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1015,7 +1015,7 @@ impl AsRef<str> for String {
10151015
impl<'a> From<&'a str> for String {
10161016
#[inline]
10171017
fn from(s: &'a str) -> String {
1018-
s.to_string()
1018+
String { vec: <[_]>::to_vec(s.as_bytes()) }
10191019
}
10201020
}
10211021

src/libcollectionstest/string.rs

+28-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ use std::iter::repeat;
1313
use std::str::Utf8Error;
1414
use std::string::as_string;
1515

16-
use test::Bencher;
16+
use test::{self, Bencher};
1717

1818
#[test]
1919
fn test_as_string() {
@@ -450,3 +450,30 @@ fn bench_exact_size_shrink_to_fit(b: &mut Bencher) {
450450
r
451451
});
452452
}
453+
454+
#[bench]
455+
fn bench_from_str(b: &mut Bencher) {
456+
let s = "Hello there, the quick brown fox jumped over the lazy dog! \
457+
Lorem ipsum dolor sit amet, consectetur. ";
458+
b.iter(|| {
459+
test::black_box(String::from_str(s));
460+
})
461+
}
462+
463+
#[bench]
464+
fn bench_from(b: &mut Bencher) {
465+
let s = "Hello there, the quick brown fox jumped over the lazy dog! \
466+
Lorem ipsum dolor sit amet, consectetur. ";
467+
b.iter(|| {
468+
test::black_box(String::from(s));
469+
})
470+
}
471+
472+
#[bench]
473+
fn bench_to_string(b: &mut Bencher) {
474+
let s = "Hello there, the quick brown fox jumped over the lazy dog! \
475+
Lorem ipsum dolor sit amet, consectetur. ";
476+
b.iter(|| {
477+
test::black_box(s.to_string());
478+
})
479+
}

0 commit comments

Comments
 (0)