From d824de1935ac80982ec0f14d18c491aa47dcbe09 Mon Sep 17 00:00:00 2001 From: Erick Tryzelaar Date: Thu, 16 Apr 2015 21:46:22 -0700 Subject: [PATCH] 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. --- src/libcollections/string.rs | 2 +- src/libcollectionstest/string.rs | 29 ++++++++++++++++++++++++++++- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/libcollections/string.rs b/src/libcollections/string.rs index 51ce5564c49c5..886b14d8cfd9d 100644 --- a/src/libcollections/string.rs +++ b/src/libcollections/string.rs @@ -1015,7 +1015,7 @@ impl AsRef 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()) } } } diff --git a/src/libcollectionstest/string.rs b/src/libcollectionstest/string.rs index 3184f842e9ae9..389fe85eb72cd 100644 --- a/src/libcollectionstest/string.rs +++ b/src/libcollectionstest/string.rs @@ -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() { @@ -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()); + }) +}