]> git.lizzy.rs Git - rust.git/commitdiff
collections: Move optimized String::from_str to String::from
authorErick Tryzelaar <erick.tryzelaar@gmail.com>
Sun, 19 Apr 2015 17:59:06 +0000 (10:59 -0700)
committerErick Tryzelaar <erick.tryzelaar@gmail.com>
Sun, 19 Apr 2015 17:59:06 +0000 (10:59 -0700)
This implementation is currently about 3-4 times faster than using
the `.to_string()` based approach.

src/libcollections/string.rs
src/libcollectionstest/string.rs

index 74af5783fa8052799b6a029149f6552074a89240..81710286fde21311ecc577b4e47d1a4ff6d930b7 100644 (file)
@@ -1013,9 +1013,20 @@ fn as_ref(&self) -> &str {
 
 #[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)");
     }
 }
 
index 1bac3a529809cc57e68afb59968fec3d2e2b8254..d842d1e7f27c04541194864f827cf647d16e9823 100644 (file)
@@ -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()
+    })
+}