refactor: remove `typed_insert` when appending cache-control header
it improves the performance of `control_headers` module in general for
this particular case.
Diff
.gitignore | 3 ++-
benches/Cargo.toml | 15 +++++++++++++++
benches/control_headers.rs | 19 +++++++++++++++++++
src/control_headers.rs | 20 ++++++++++----------
4 files changed, 46 insertions(+), 11 deletions(-)
@@ -1,4 +1,4 @@
/target
**/target
/bin
**/*.rs.bk
**/*.log
@@ -19,6 +19,7 @@
**/*empty*
**/*.json
**/*.csv
/benches/Cargo.lock
release
.vscode
TODO
@@ -0,0 +1,15 @@
[package]
name = "benches"
version = "0.0.0"
publish = false
edition = "2021"
[dependencies]
static-web-server = { version = "2", path = "../", features = ["default"] }
criterion = "0.5"
hyper = { version = "0.14", features = ["stream", "http1", "http2", "tcp", "server"] }
[[bench]]
name = "control_headers"
path = "control_headers.rs"
harness = false
@@ -0,0 +1,19 @@
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
use hyper::{Body, Response, StatusCode};
use static_web_server::control_headers;
fn append_headers_benchmark(c: &mut Criterion) {
let mut resp = Response::new(Body::empty());
*resp.status_mut() = StatusCode::OK;
let uri_path: &str = "assets/image.jpg";
c.bench_with_input(
BenchmarkId::new("uri_path_input", uri_path),
&uri_path,
|b, &s| b.iter(|| control_headers::append_headers(s, &mut resp)),
);
}
criterion_group!(control_headers_bench, append_headers_benchmark);
criterion_main!(control_headers_bench);
@@ -7,7 +7,6 @@
use headers::{CacheControl, HeaderMapExt};
use hyper::{Body, Response};
@@ -36,15 +35,16 @@ pub fn append_headers(uri: &str, resp: &mut Response<Body>) {
}
}
let cache_control = CacheControl::new()
.with_public()
.with_max_age(duration_from_secs(max_age));
resp.headers_mut().typed_insert(cache_control);
}
fn duration_from_secs(secs: u64) -> std::time::Duration {
std::time::Duration::from_secs(std::cmp::min(secs, u32::MAX as u64))
resp.headers_mut().insert(
"cache-control",
format!(
"public, max-age={}",
std::cmp::min(max_age, u32::MAX as u64)
)
.parse()
.unwrap(),
);
}