Skip to content

Commit 02da530

Browse files
committed
perf: Reduce the number of String allocations
1 parent e4daf00 commit 02da530

File tree

2 files changed

+20
-8
lines changed

2 files changed

+20
-8
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@
22

33
## [Unreleased]
44

5+
### Performance
6+
7+
- Reduce the number of `String` allocations.
8+
59
## [0.3.1] - 2020-06-25
610

711
### Changed

src/lib.rs

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -278,10 +278,14 @@ fn process_css(document: &NodeRef, css: &str) -> Result<()> {
278278
let style = if let Some(existing_style) = attributes.get("style") {
279279
merge_styles(existing_style, &rule.declarations)?
280280
} else {
281-
rule.declarations
282-
.iter()
283-
.map(|&(ref key, value)| format!("{}:{};", key, value))
284-
.collect()
281+
let mut final_styles = String::with_capacity(32);
282+
for (name, value) in rule.declarations.iter() {
283+
final_styles.push_str(name);
284+
final_styles.push(':');
285+
final_styles.push_str(value);
286+
final_styles.push(';');
287+
}
288+
final_styles
285289
};
286290
attributes.insert("style", style);
287291
}
@@ -332,8 +336,12 @@ fn merge_styles(existing_style: &str, new_styles: &[parser::Declaration]) -> Res
332336
styles.insert(property.to_string(), value);
333337
}
334338
// Create a new declarations list
335-
Ok(styles
336-
.into_iter()
337-
.map(|(key, value)| format!("{}:{};", key, value))
338-
.collect::<String>())
339+
let mut final_styles = String::with_capacity(32);
340+
for (name, value) in &styles {
341+
final_styles.push_str(name.as_str());
342+
final_styles.push(':');
343+
final_styles.push_str(value);
344+
final_styles.push(';');
345+
}
346+
Ok(final_styles)
339347
}

0 commit comments

Comments
 (0)