Przeglądaj źródła

Merge pull request #760 from AaronO/perf/url-parse-avoid-trivial-reallocs

perf(url): avoid trivial reallocs
Valentin Gosu 4 lat temu
rodzic
commit
91f01bd3d2
3 zmienionych plików z 14 dodań i 8 usunięć
  1. 1 1
      idna/src/uts46.rs
  2. 8 1
      url/benches/parse_url.rs
  3. 5 6
      url/src/parser.rs

+ 1 - 1
idna/src/uts46.rs

@@ -554,7 +554,7 @@ impl Config {
 
     /// http://www.unicode.org/reports/tr46/#ToASCII
     pub fn to_ascii(self, domain: &str) -> Result<String, Errors> {
-        let mut result = String::new();
+        let mut result = String::with_capacity(domain.len());
         let mut codec = Idna::new(self);
         codec.to_ascii(domain, &mut result).map(|()| result)
     }

+ 8 - 1
url/benches/parse_url.rs

@@ -12,5 +12,12 @@ fn short(bench: &mut Bencher) {
     bench.iter(|| black_box(url).parse::<Url>().unwrap());
 }
 
-benchmark_group!(benches, short);
+fn long(bench: &mut Bencher) {
+    let url = "https://example.com/parkbench?tre=es&st=uff";
+
+    bench.bytes = url.len() as u64;
+    bench.iter(|| black_box(url).parse::<Url>().unwrap());
+}
+
+benchmark_group!(benches, short, long);
 benchmark_main!(benches);

+ 5 - 6
url/src/parser.rs

@@ -1216,13 +1216,11 @@ impl<'a> Parser<'a> {
                     }
                 }
             }
-            // Going from &str to String to &str to please the 1.33.0 borrow checker
-            let before_slash_string = if ends_with_slash {
-                self.serialization[segment_start..self.serialization.len() - 1].to_owned()
+            let segment_before_slash = if ends_with_slash {
+                &self.serialization[segment_start..self.serialization.len() - 1]
             } else {
-                self.serialization[segment_start..self.serialization.len()].to_owned()
+                &self.serialization[segment_start..self.serialization.len()]
             };
-            let segment_before_slash: &str = &before_slash_string;
             match segment_before_slash {
                 // If buffer is a double-dot path segment, shorten url’s path,
                 ".." | "%2e%2e" | "%2e%2E" | "%2E%2e" | "%2E%2E" | "%2e." | "%2E." | ".%2e"
@@ -1412,7 +1410,8 @@ impl<'a> Parser<'a> {
         scheme_end: u32,
         mut input: Input<'i>,
     ) -> Option<Input<'i>> {
-        let mut query = String::new(); // FIXME: use a streaming decoder instead
+        let len = input.chars.as_str().len();
+        let mut query = String::with_capacity(len); // FIXME: use a streaming decoder instead
         let mut remaining = None;
         while let Some(c) = input.next() {
             if c == '#' && self.context == Context::UrlParser {