str: optimize with_capacity

before:

test bench_with_capacity ... bench: 104 ns/iter (+/- 4)

after:

test bench_with_capacity ... bench: 56 ns/iter (+/- 1)
This commit is contained in:
Daniel Micay 2013-08-10 13:32:05 -04:00
parent 2afed31ecc
commit 768c9a43ab

View File

@ -807,6 +807,7 @@ pub fn from_utf16(v: &[u16]) -> ~str {
/// Allocates a new string with the specified capacity. The string returned is /// Allocates a new string with the specified capacity. The string returned is
/// the empty string, but has capacity for much more. /// the empty string, but has capacity for much more.
#[cfg(stage0)]
#[inline] #[inline]
pub fn with_capacity(capacity: uint) -> ~str { pub fn with_capacity(capacity: uint) -> ~str {
let mut buf = ~""; let mut buf = ~"";
@ -814,6 +815,16 @@ pub fn with_capacity(capacity: uint) -> ~str {
buf 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 /// As char_len but for a slice of a string
/// ///
/// # Arguments /// # Arguments
@ -3700,7 +3711,7 @@ mod tests {
#[cfg(test)] #[cfg(test)]
mod bench { mod bench {
use extra::test::BenchHarness; use extra::test::BenchHarness;
use str; use super::*;
#[bench] #[bench]
fn is_utf8_100_ascii(bh: &mut BenchHarness) { fn is_utf8_100_ascii(bh: &mut BenchHarness) {
@ -3710,7 +3721,7 @@ mod bench {
assert_eq!(100, s.len()); assert_eq!(100, s.len());
do bh.iter { do bh.iter {
str::is_utf8(s); is_utf8(s);
} }
} }
@ -3719,7 +3730,7 @@ mod bench {
let s = bytes!("𐌀𐌖𐌋𐌄𐌑𐌉ปรدولة الكويتทศไทย中华𐍅𐌿𐌻𐍆𐌹𐌻𐌰"); let s = bytes!("𐌀𐌖𐌋𐌄𐌑𐌉ปรدولة الكويتทศไทย中华𐍅𐌿𐌻𐍆𐌹𐌻𐌰");
assert_eq!(100, s.len()); assert_eq!(100, s.len());
do bh.iter { 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); s.map_chars(|c| ((c as uint) + 1) as char);
} }
} }
#[bench]
fn bench_with_capacity(bh: &mut BenchHarness) {
do bh.iter {
with_capacity(100);
}
}
} }