Skip to content

Commit 466a5b5

Browse files
committed
str: optimize with_capacity
before: test bench_with_capacity ... bench: 104 ns/iter (+/- 4) after: test bench_with_capacity ... bench: 56 ns/iter (+/- 1)
1 parent 7a29aa5 commit 466a5b5

File tree

1 file changed

+21
-3
lines changed

1 file changed

+21
-3
lines changed

src/libstd/str.rs

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -807,13 +807,24 @@ pub fn from_utf16(v: &[u16]) -> ~str {
807807

808808
/// Allocates a new string with the specified capacity. The string returned is
809809
/// the empty string, but has capacity for much more.
810+
#[cfg(stage0)]
810811
#[inline]
811812
pub fn with_capacity(capacity: uint) -> ~str {
812813
let mut buf = ~"";
813814
buf.reserve(capacity);
814815
buf
815816
}
816817

818+
/// Allocates a new string with the specified capacity. The string returned is
819+
/// the empty string, but has capacity for much more.
820+
#[cfg(not(stage0))]
821+
#[inline]
822+
pub fn with_capacity(capacity: uint) -> ~str {
823+
unsafe {
824+
cast::transmute(vec::with_capacity::<~[u8]>(capacity))
825+
}
826+
}
827+
817828
/// As char_len but for a slice of a string
818829
///
819830
/// # Arguments
@@ -3701,7 +3712,7 @@ mod tests {
37013712
#[cfg(test)]
37023713
mod bench {
37033714
use extra::test::BenchHarness;
3704-
use str;
3715+
use super::*;
37053716
37063717
#[bench]
37073718
fn is_utf8_100_ascii(bh: &mut BenchHarness) {
@@ -3711,7 +3722,7 @@ mod bench {
37113722
37123723
assert_eq!(100, s.len());
37133724
do bh.iter {
3714-
str::is_utf8(s);
3725+
is_utf8(s);
37153726
}
37163727
}
37173728
@@ -3720,7 +3731,7 @@ mod bench {
37203731
let s = bytes!("𐌀𐌖𐌋𐌄𐌑𐌉ปรدولة الكويتทศไทย中华𐍅𐌿𐌻𐍆𐌹𐌻𐌰");
37213732
assert_eq!(100, s.len());
37223733
do bh.iter {
3723-
str::is_utf8(s);
3734+
is_utf8(s);
37243735
}
37253736
}
37263737
@@ -3743,4 +3754,11 @@ mod bench {
37433754
s.map_chars(|c| ((c as uint) + 1) as char);
37443755
}
37453756
}
3757+
3758+
#[bench]
3759+
fn bench_with_capacity(bh: &mut BenchHarness) {
3760+
do bh.iter {
3761+
with_capacity(100);
3762+
}
3763+
}
37463764
}

0 commit comments

Comments
 (0)