Last active
March 30, 2023 08:23
-
-
Save Mivik/1e46259a80ce0dddd053181ac1aa0bbe to your computer and use it in GitHub Desktop.
SQLx vs tokio-postgres benchmark
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use criterion::{criterion_group, criterion_main, Criterion}; | |
use sqlx::{ | |
postgres::{PgConnectOptions, PgPoolOptions}, | |
ConnectOptions, | |
}; | |
use tokio::runtime::Runtime; | |
use tokio_postgres::NoTls; | |
pub fn rand_token() -> String { | |
use rand::{distributions::Alphanumeric, Rng}; | |
rand::thread_rng() | |
.sample_iter(&Alphanumeric) | |
.take(32) | |
.map(char::from) | |
.collect() | |
} | |
pub fn sqlx_vs_postgres(c: &mut Criterion) { | |
const CONNECT_OPTS: &str = "XXX"; | |
const DATABASE_URL: &str = "XXX"; | |
c.bench_function("postgres", |b| { | |
let rt = Runtime::new().unwrap(); | |
let (client, connection) = rt | |
.block_on(tokio_postgres::connect(CONNECT_OPTS, NoTls)) | |
.unwrap(); | |
rt.spawn(connection); | |
b.to_async(rt).iter(|| async { | |
client | |
.query( | |
"select db_id from lc_map where lc_id = $1", | |
&[&rand_token()], | |
) | |
.await | |
.unwrap(); | |
}); | |
}); | |
c.bench_function("sqlx", |b| { | |
let mut opt: PgConnectOptions = DATABASE_URL.parse().unwrap(); | |
opt.disable_statement_logging(); | |
let rt = Runtime::new().unwrap(); | |
let db = rt | |
.block_on(PgPoolOptions::new().max_connections(5).connect_with(opt)) | |
.unwrap(); | |
b.to_async(rt).iter(|| async { | |
sqlx::query("select db_id from lc_map where lc_id = $1") | |
.bind(rand_token()) | |
.fetch_optional(&db) | |
.await | |
.unwrap(); | |
}); | |
}); | |
} | |
criterion_group!(benches, sqlx_vs_postgres); | |
criterion_main!(benches); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment