Skip to content

Commit 97ff2d6

Browse files
authored
Rollup merge of rust-lang#55384 - nnethercote:better-integer_lit-float_lit, r=michaelwoerister
Avoid unnecessary allocations in `float_lit` and `integer_lit`. This commit avoids an allocation when parsing any float and integer literals that don't involved underscores. This reduces the number of allocations done for the `tuple-stress` benchmark by 10%, reducing its instruction count by just under 1%.
2 parents 4e88b73 + eb637d2 commit 97ff2d6

File tree

1 file changed

+19
-4
lines changed

1 file changed

+19
-4
lines changed

src/libsyntax/parse/mod.rs

+19-4
Original file line numberDiff line numberDiff line change
@@ -494,8 +494,17 @@ fn float_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
494494
-> Option<ast::LitKind> {
495495
debug!("float_lit: {:?}, {:?}", s, suffix);
496496
// FIXME #2252: bounds checking float literals is deferred until trans
497-
let s = s.chars().filter(|&c| c != '_').collect::<String>();
498-
filtered_float_lit(Symbol::intern(&s), suffix, diag)
497+
498+
// Strip underscores without allocating a new String unless necessary.
499+
let s2;
500+
let s = if s.chars().any(|c| c == '_') {
501+
s2 = s.chars().filter(|&c| c != '_').collect::<String>();
502+
&s2
503+
} else {
504+
s
505+
};
506+
507+
filtered_float_lit(Symbol::intern(s), suffix, diag)
499508
}
500509

501510
/// Parse a string representing a byte literal into its final form. Similar to `char_lit`
@@ -591,8 +600,14 @@ fn integer_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler)>)
591600
-> Option<ast::LitKind> {
592601
// s can only be ascii, byte indexing is fine
593602

594-
let s2 = s.chars().filter(|&c| c != '_').collect::<String>();
595-
let mut s = &s2[..];
603+
// Strip underscores without allocating a new String unless necessary.
604+
let s2;
605+
let mut s = if s.chars().any(|c| c == '_') {
606+
s2 = s.chars().filter(|&c| c != '_').collect::<String>();
607+
&s2
608+
} else {
609+
s
610+
};
596611

597612
debug!("integer_lit: {}, {:?}", s, suffix);
598613

0 commit comments

Comments
 (0)