Skip to content

Commit b836e07

Browse files
committed
perf: Awards::parse use as_i64() and Vec::with_capacity to avoid allocs
1 parent 5ad661c commit b836e07

1 file changed

Lines changed: 9 additions & 15 deletions

File tree

src/utils.rs

Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -525,22 +525,16 @@ impl std::fmt::Display for Awards {
525525
impl Awards {
526526
/// Convert Reddit awards JSON to Awards struct
527527
pub fn parse(items: &Value) -> Self {
528-
let parsed = items.as_array().unwrap_or(&Vec::new()).iter().fold(Vec::new(), |mut awards, item| {
529-
let name = item["name"].as_str().unwrap_or_default().to_string();
530-
let icon_url = format_url(item["resized_icons"][0]["url"].as_str().unwrap_or_default());
531-
let description = item["description"].as_str().unwrap_or_default().to_string();
532-
let count: i64 = i64::from_str(&item["count"].to_string()).unwrap_or(1);
533-
534-
awards.push(Award {
535-
name,
536-
icon_url,
537-
description,
538-
count,
528+
let arr = items.as_array().map(|v| v.as_slice()).unwrap_or_default();
529+
let mut parsed = Vec::with_capacity(arr.len());
530+
for item in arr {
531+
parsed.push(Award {
532+
name: item["name"].as_str().unwrap_or_default().to_string(),
533+
icon_url: format_url(item["resized_icons"][0]["url"].as_str().unwrap_or_default()),
534+
description: item["description"].as_str().unwrap_or_default().to_string(),
535+
count: item["count"].as_i64().unwrap_or(1),
539536
});
540-
541-
awards
542-
});
543-
537+
}
544538
Self(parsed)
545539
}
546540
}

0 commit comments

Comments
 (0)