Skip to content

Commit 2d67f90

Browse files
perf: shorten path and use references
1 parent e1e7b9f commit 2d67f90

File tree

1 file changed

+7
-5
lines changed

1 file changed

+7
-5
lines changed

frameworks/Rust/axum/src/main_sqlx.rs

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
mod common;
22
mod sqlx;
33

4+
use std::sync::Arc;
5+
46
use ::sqlx::PgPool;
57
use axum::{
68
extract::{Query, State},
@@ -56,7 +58,7 @@ async fn queries(
5658
let ids = random_ids(&mut rng, count);
5759
let mut worlds: Vec<World> = Vec::with_capacity(count);
5860

59-
for id in ids {
61+
for id in &ids {
6062
let world: World = ::sqlx::query_as(common::SELECT_WORLD_BY_ID)
6163
.bind(id)
6264
.fetch_one(&mut *db.acquire().await.unwrap())
@@ -96,7 +98,7 @@ async fn cache(
9698
) -> impl IntoResponse {
9799
let count = parse_params(params);
98100
let mut rng = SmallRng::from_rng(&mut thread_rng()).unwrap();
99-
let mut worlds: Vec<Option<World>> = Vec::with_capacity(count);
101+
let mut worlds: Vec<Option<Arc<World>>> = Vec::with_capacity(count);
100102

101103
for id in random_ids(&mut rng, count) {
102104
worlds.push(cache.get(&id).await);
@@ -113,15 +115,15 @@ async fn preload_cache(AppState { db, cache }: &AppState) {
113115
.expect("error loading worlds");
114116

115117
for world in worlds {
116-
cache.insert(world.id, world).await;
118+
cache.insert(world.id, Arc::new(world)).await;
117119
}
118120
}
119121

120122
/// Application state
121123
#[derive(Clone)]
122124
struct AppState {
123125
db: PgPool,
124-
cache: Cache<i32, World>,
126+
cache: Cache<i32, Arc<World>>,
125127
}
126128

127129
#[tokio::main]
@@ -147,7 +149,7 @@ async fn main() {
147149
.route("/fortunes", get(fortunes))
148150
.route("/db", get(db))
149151
.route("/queries", get(queries))
150-
.route("/cached-queries", get(cache))
152+
.route("/cached", get(cache))
151153
.with_state(state);
152154

153155
server::serve_hyper(app, Some(8000)).await

0 commit comments

Comments
 (0)