File tree Expand file tree Collapse file tree 2 files changed +15
-10
lines changed Expand file tree Collapse file tree 2 files changed +15
-10
lines changed Original file line number Diff line number Diff line change @@ -281,17 +281,20 @@ impl<'a> Arguments<'a> {
281281 let pieces_length: W < usize > = self . pieces . iter ( )
282282 . map ( |x| W ( x. len ( ) ) ) . sum ( ) ;
283283
284- // If they are any arguments to format, the string will most likely
285- // double in size. So we're pre-doubling it here.
286- let multiplier = if self . args . is_empty ( ) { W ( 1 ) } else { W ( 2 ) } ;
287-
288- let capacity = multiplier * pieces_length;
289- if multiplier == W ( 2 ) && ( W ( 1 ) ..W ( 8 ) ) . contains ( capacity) {
290- // Allocations smaller than 8 don't really make sense for String.
291- 8
284+ if self . args . is_empty ( ) {
285+ pieces_length. 0
286+ } else if self . pieces [ 0 ] == "" && pieces_length < W ( 16 ) {
287+ // If the format string starts with an argument,
288+ // don't preallocate anything, unless length
289+ // of pieces is significant.
290+ 0
292291 } else {
293- capacity. 0
292+ // There are some arguments, so any additional push
293+ // will reallocate the string. To avoid that,
294+ // we're "pre-doubling" the capacity here.
295+ ( pieces_length * W ( 2 ) ) . 0
294296 }
297+
295298 }
296299}
297300
Original file line number Diff line number Diff line change @@ -31,8 +31,10 @@ fn test_pointer_formats_data_pointer() {
3131
3232#[ test]
3333fn test_estimated_capacity ( ) {
34+ assert_eq ! ( format_args!( "" ) . estimated_capacity( ) , 0 ) ;
3435 assert_eq ! ( format_args!( "{}" , "" ) . estimated_capacity( ) , 0 ) ;
3536 assert_eq ! ( format_args!( "Hello" ) . estimated_capacity( ) , 5 ) ;
3637 assert_eq ! ( format_args!( "Hello, {}!" , "" ) . estimated_capacity( ) , 16 ) ;
37- assert_eq ! ( format_args!( "{}, hello!" , "World" ) . estimated_capacity( ) , 16 ) ;
38+ assert_eq ! ( format_args!( "{}, hello!" , "World" ) . estimated_capacity( ) , 0 ) ;
39+ assert_eq ! ( format_args!( "{}. 16-bytes piece" , "World" ) . estimated_capacity( ) , 32 ) ;
3840}
You can’t perform that action at this time.
0 commit comments