Skip to content

Commit 2df9a96

Browse files
committed
traits: small performance improvements
1 parent a564e3f commit 2df9a96

File tree

1 file changed

+33
-24
lines changed

1 file changed

+33
-24
lines changed

src/traits.rs

Lines changed: 33 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -17,17 +17,18 @@ impl HeadersTraits for IndexMapSSR {
1717
self.clone()
1818
}
1919
fn to_headermap(&self) -> HeaderMap {
20-
self.iter()
21-
.map(|(k, v)| {
22-
(
23-
HeaderName::from_bytes(k.as_bytes())
24-
.unwrap_or_else(|k| panic!("Invalid header name: {k:?}")),
25-
HeaderValue::from_bytes(v.as_bytes())
26-
.unwrap_or_else(|v| panic!("Invalid header value: {v:?}")),
27-
)
28-
})
29-
.collect()
20+
let mut header_map = HeaderMap::with_capacity(self.len());
21+
for (k, v) in self {
22+
header_map.insert(
23+
HeaderName::from_bytes(k.as_bytes())
24+
.unwrap_or_else(|k| panic!("Invalid header name: {k:?}")),
25+
HeaderValue::from_bytes(v.as_bytes())
26+
.unwrap_or_else(|v| panic!("Invalid header value: {v:?}")),
27+
);
28+
}
29+
header_map
3030
}
31+
3132
fn insert_key_value(&mut self, key: String, value: String) -> Result<(), Error> {
3233
self.insert(key.to_string(), value.to_string());
3334
Ok(())
@@ -36,16 +37,18 @@ impl HeadersTraits for IndexMapSSR {
3637

3738
impl HeadersTraits for HeaderMap {
3839
fn to_indexmap(&self) -> IndexMapSSR {
39-
self.iter()
40-
.map(|(k, v)| {
41-
(
42-
k.to_string(),
43-
v.to_str()
44-
.unwrap_or_else(|v| panic!("Invalid header value: {v:?}"))
45-
.to_string(),
46-
)
47-
})
48-
.collect()
40+
let mut index_map =
41+
IndexMapSSR::with_capacity_and_hasher(self.len(), RandomState::default());
42+
for (key, value) in self {
43+
index_map.insert(
44+
key.as_str().to_string(),
45+
value
46+
.to_str()
47+
.unwrap_or_else(|v| panic!("Invalid header value: {v:?}"))
48+
.to_string(),
49+
);
50+
}
51+
index_map
4952
}
5053

5154
fn to_headermap(&self) -> HeaderMap {
@@ -68,9 +71,15 @@ pub trait CookiesTraits {
6871

6972
impl CookiesTraits for IndexMapSSR {
7073
fn to_string(&self) -> String {
71-
self.iter()
72-
.map(|(k, v)| format!("{}={}", k, v))
73-
.collect::<Vec<String>>()
74-
.join("; ")
74+
let mut result = String::with_capacity(self.len() * 40);
75+
for (k, v) in self {
76+
if !result.is_empty() {
77+
result.push_str("; ");
78+
}
79+
result.push_str(k);
80+
result.push('=');
81+
result.push_str(v);
82+
}
83+
result
7584
}
7685
}

0 commit comments

Comments
 (0)