From 768c9a43ab4c1fa53f21d1be30c72fde6b2367de Mon Sep 17 00:00:00 2001 From: Daniel Micay Date: Sat, 10 Aug 2013 13:32:05 -0400 Subject: [PATCH] str: optimize `with_capacity` before: test bench_with_capacity ... bench: 104 ns/iter (+/- 4) after: test bench_with_capacity ... bench: 56 ns/iter (+/- 1) --- src/libstd/str.rs | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/src/libstd/str.rs b/src/libstd/str.rs index 26a00cca4c8..81c9cde312e 100644 --- a/src/libstd/str.rs +++ b/src/libstd/str.rs @@ -807,6 +807,7 @@ pub fn from_utf16(v: &[u16]) -> ~str { /// Allocates a new string with the specified capacity. The string returned is /// the empty string, but has capacity for much more. +#[cfg(stage0)] #[inline] pub fn with_capacity(capacity: uint) -> ~str { let mut buf = ~""; @@ -814,6 +815,16 @@ pub fn with_capacity(capacity: uint) -> ~str { buf } +/// Allocates a new string with the specified capacity. The string returned is +/// the empty string, but has capacity for much more. +#[cfg(not(stage0))] +#[inline] +pub fn with_capacity(capacity: uint) -> ~str { + unsafe { + cast::transmute(vec::with_capacity::<~[u8]>(capacity)) + } +} + /// As char_len but for a slice of a string /// /// # Arguments @@ -3700,7 +3711,7 @@ mod tests { #[cfg(test)] mod bench { use extra::test::BenchHarness; - use str; + use super::*; #[bench] fn is_utf8_100_ascii(bh: &mut BenchHarness) { @@ -3710,7 +3721,7 @@ mod bench { assert_eq!(100, s.len()); do bh.iter { - str::is_utf8(s); + is_utf8(s); } } @@ -3719,7 +3730,7 @@ mod bench { let s = bytes!("πŒ€πŒ–πŒ‹πŒ„πŒ‘πŒ‰ΰΈ›ΰΈ£Ψ―ΩˆΩ„Ψ© Ψ§Ω„ΩƒΩˆΩŠΨͺΰΈ—ΰΈ¨ΰΉ„ΰΈ—ΰΈ’δΈ­εŽπ…πŒΏπŒ»π†πŒΉπŒ»πŒ°"); assert_eq!(100, s.len()); do bh.iter { - str::is_utf8(s); + is_utf8(s); } } @@ -3742,4 +3753,11 @@ mod bench { s.map_chars(|c| ((c as uint) + 1) as char); } } + + #[bench] + fn bench_with_capacity(bh: &mut BenchHarness) { + do bh.iter { + with_capacity(100); + } + } }