Skip to content

Commit 1479763

Browse files
committed
Try reusing memory
Fix #10
1 parent b6671ce commit 1479763

1 file changed

Lines changed: 15 additions & 15 deletions

File tree

src/bin/basic_batched.rs

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -46,36 +46,36 @@ fn faker(tx: &Transaction, count: i64) {
4646

4747
let mut stmt_with_area = tx.prepare_cached(st1.as_str()).unwrap();
4848
let mut stmt = tx.prepare_cached(st2.as_str()).unwrap();
49+
let mut params_with_area = Vec::with_capacity(min_batch_size as usize);
50+
let mut param_values: Vec<&dyn ToSql> = Vec::with_capacity(min_batch_size as usize * 3);
4951
for _ in 0..(count / min_batch_size) {
5052
let with_area = common::get_random_bool();
5153
let age = common::get_random_age();
5254
let is_active = common::get_random_active();
53-
let mut param_values: Vec<_> = Vec::new();
5455
if with_area {
55-
// lets prepare the batch
56-
let mut vector = Vec::<(String, i8, i8)>::new();
5756
for _ in 0..min_batch_size {
5857
let area_code = common::get_random_area_code();
59-
vector.push((area_code, age, is_active));
58+
params_with_area.push((area_code,));
6059
}
61-
for batch in vector.iter() {
62-
param_values.push(&batch.0 as &dyn ToSql);
63-
param_values.push(&batch.1 as &dyn ToSql);
64-
param_values.push(&batch.2 as &dyn ToSql);
60+
for params in &params_with_area {
61+
// Safety: extend lifetime of params as it will be cleared at the end of the loop
62+
// to reuse memory
63+
param_values.push(unsafe { std::mem::transmute(&params.0 as &dyn ToSql) });
64+
param_values.push(unsafe { std::mem::transmute(&age as &dyn ToSql) });
65+
param_values.push(unsafe { std::mem::transmute(&is_active as &dyn ToSql) });
6566
}
6667
stmt_with_area.execute(&*param_values).unwrap();
68+
params_with_area.clear();
6769
} else {
68-
// lets prepare the batch
69-
let mut vector = Vec::<(i8, i8)>::new();
7070
for _ in 0..min_batch_size {
71-
vector.push((age, is_active));
72-
}
73-
for batch in vector.iter() {
74-
param_values.push(&batch.0 as &dyn ToSql);
75-
param_values.push(&batch.1 as &dyn ToSql);
71+
// Safety: extend lifetime of params as it will be cleared at the end of the loop
72+
// to reuse memory
73+
param_values.push(unsafe { std::mem::transmute(&age as &dyn ToSql) });
74+
param_values.push(unsafe { std::mem::transmute(&is_active as &dyn ToSql) });
7675
}
7776
stmt.execute(&*param_values).unwrap();
7877
}
78+
param_values.clear();
7979
}
8080
}
8181

0 commit comments

Comments
 (0)