Skip to content

Commit 4b41e75

Browse files
committed
chore: reduce realloc
1 parent 112fb17 commit 4b41e75

File tree

15 files changed

+41
-32
lines changed

15 files changed

+41
-32
lines changed

crates/rbuilder/src/backtest/backtest_build_block.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -319,7 +319,7 @@ fn print_onchain_block_data(
319319
orders: &[Order],
320320
block_data: &BlockData,
321321
) {
322-
let mut executed_orders = Vec::new();
322+
let mut executed_orders = Vec::with_capacity(tx_sim_results.len());
323323

324324
let txs_to_idx: HashMap<_, _> = tx_sim_results
325325
.iter()

crates/rbuilder/src/backtest/fetch/flashbots_db.rs

+5-7
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
1-
use crate::backtest::BuiltBlockData;
2-
use crate::primitives::OrderId;
31
use crate::{
42
backtest::{
53
fetch::data_source::{BlockRef, DataSource, DatasourceData},
6-
OrdersWithTimestamp,
4+
BuiltBlockData, OrdersWithTimestamp,
75
},
86
primitives::{
97
serialize::{RawBundle, RawOrder, RawShareBundle, TxEncoding},
10-
Order, SimValue,
8+
Order, OrderId, SimValue,
119
},
1210
};
1311
use alloy_primitives::I256;
@@ -19,8 +17,7 @@ use bigdecimal::{
1917
use eyre::WrapErr;
2018
use reth_primitives::{Bytes, B256, U256, U64};
2119
use sqlx::postgres::PgPool;
22-
use std::collections::HashSet;
23-
use std::{ops::Mul, str::FromStr};
20+
use std::{collections::HashSet, ops::Mul, str::FromStr};
2421
use time::{OffsetDateTime, PrimitiveDateTime};
2522
use tracing::trace;
2623
use uuid::Uuid;
@@ -333,7 +330,8 @@ impl RelayDB {
333330
.fetch_all(&self.pool)
334331
.await?;
335332

336-
let mut included_orders = Vec::new();
333+
let mut included_orders =
334+
Vec::with_capacity(included_bundles.len() + included_sbundles.len());
337335
for (bundle_uuid,) in included_bundles {
338336
let order_id = OrderId::Bundle(bundle_uuid);
339337
included_orders.push(order_id);

crates/rbuilder/src/backtest/redistribute/mod.rs

+6-2
Original file line numberDiff line numberDiff line change
@@ -293,7 +293,7 @@ where
293293
})
294294
.collect::<Vec<_>>();
295295

296-
let mut simplified_orders = Vec::new();
296+
let mut simplified_orders = Vec::with_capacity(included_orders_available.len());
297297

298298
for available_order in included_orders_available {
299299
simplified_orders.push(SimplifiedOrder::new_from_order(&available_order.order));
@@ -880,7 +880,11 @@ fn calc_inclusion_change(
880880
exclusion_result: &ExclusionResult,
881881
included_before: &[(OrderId, U256)],
882882
) -> Vec<OrderInclusionChange> {
883-
let mut result = Vec::new();
883+
let mut result = Vec::with_capacity(
884+
exclusion_result.new_orders_included.len()
885+
+ exclusion_result.new_orders_failed.len()
886+
+ exclusion_result.orders_profit_changed.len(),
887+
);
884888
for (id, profit_after) in &exclusion_result.new_orders_included {
885889
result.push((
886890
*id,

crates/rbuilder/src/backtest/redistribute/redistribution_algo.rs

+5-4
Original file line numberDiff line numberDiff line change
@@ -141,10 +141,11 @@ pub fn calculate_redistribution(data: RedistributionCalculator) -> Redistributio
141141
}
142142

143143
let mut total_value_redistributed = U256::ZERO;
144-
let mut redistribution_entity_result = Vec::new();
144+
let mut redistribution_entity_result = Vec::with_capacity(n);
145145
for i in 0..n {
146-
let mut order_id_vector = Vec::new();
147-
let mut order_contrib_vector = Vec::new();
146+
let mut order_id_vector = Vec::with_capacity(data.identity_data[i].included_orders.len());
147+
let mut order_contrib_vector =
148+
Vec::with_capacity(data.identity_data[i].included_orders.len());
148149
for landed_order in &data.identity_data[i].included_orders {
149150
order_id_vector.push(landed_order.id);
150151
order_contrib_vector.push(landed_order.realized_value);
@@ -230,7 +231,7 @@ fn split_value(value: U256, split_vector: &[U256]) -> Vec<U256> {
230231
if total_split.is_zero() {
231232
return split_vector.iter().map(|_| U256::ZERO).collect();
232233
}
233-
let mut result = Vec::new();
234+
let mut result = Vec::with_capacity(split_vector.len());
234235
for split in split_vector {
235236
result.push((value * split) / total_split);
236237
}

crates/rbuilder/src/building/block_orders/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,7 @@ pub fn block_orders_from_sim_orders(
197197
) -> ProviderResult<BlockOrders> {
198198
let mut onchain_nonces = vec![];
199199
for order in sim_orders {
200+
onchain_nonces.reserve_exact(order.order.nonces().len());
200201
for nonce in order.order.nonces() {
201202
let value = state_provider
202203
.account_nonce(nonce.address)?

crates/rbuilder/src/building/block_orders/test_context.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ impl<TestedSinkType: SimulatedOrderSink> TestContext<TestedSinkType> {
111111
/// tx is the same in all backruns
112112
pub fn create_multiple_sbundle_tx_br(&mut self, sbundle_count: usize) -> Vec<ShareBundle> {
113113
let tx = self.create_share_bundle_tx_bundle(TxRevertBehavior::AllowedExcluded);
114-
let mut res = Vec::new();
114+
let mut res = Vec::with_capacity(sbundle_count);
115115
for _ in 0..sbundle_count {
116116
let body = vec![
117117
tx.clone(),

crates/rbuilder/src/building/builders/parallel_builder/conflict_resolvers.rs

+9-6
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,15 @@ use std::sync::Arc;
1010
use tokio_util::sync::CancellationToken;
1111
use tracing::trace;
1212

13-
use super::simulation_cache::{CachedSimulationState, SharedSimulationCache};
14-
use super::{Algorithm, ConflictTask, ResolutionResult};
13+
use super::{
14+
simulation_cache::{CachedSimulationState, SharedSimulationCache},
15+
Algorithm, ConflictTask, ResolutionResult,
16+
};
1517

16-
use crate::building::{BlockBuildingContext, BlockState, PartialBlock};
17-
use crate::building::{ExecutionError, ExecutionResult};
18-
use crate::primitives::{OrderId, SimulatedOrder};
18+
use crate::{
19+
building::{BlockBuildingContext, BlockState, ExecutionError, ExecutionResult, PartialBlock},
20+
primitives::{OrderId, SimulatedOrder},
21+
};
1922

2023
/// Context for resolving conflicts in merging tasks.
2124
#[derive(Debug)]
@@ -352,7 +355,7 @@ fn generate_sequences_of_orders_to_try(task: &ConflictTask) -> Vec<Vec<usize>> {
352355
///
353356
/// A vector of randomly generated sequences of order indices.
354357
fn generate_random_permutations(task: &ConflictTask, seed: u64, count: usize) -> Vec<Vec<usize>> {
355-
let mut sequences_of_orders = vec![];
358+
let mut sequences_of_orders = Vec::with_capacity(count);
356359

357360
let order_group = &task.group;
358361
let mut indexes = (0..order_group.orders.len()).collect::<Vec<_>>();

crates/rbuilder/src/live_builder/block_output/bidding/wallet_balance_watcher.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ where
154154
}
155155
return Ok(Vec::new());
156156
}
157-
let mut res = Vec::new();
157+
let mut res = Vec::with_capacity(new_block.saturating_sub(self.block_number) as usize);
158158
for block_number in self.block_number + 1..=new_block {
159159
let block_info = self.get_block_info(block_number)?;
160160
res.push(block_info.as_landed_block_info(&self.builder_addr));

crates/rbuilder/src/live_builder/config.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -56,8 +56,8 @@ use reth_provider::{
5656
};
5757
use serde::Deserialize;
5858
use serde_with::{serde_as, OneOrMany};
59-
use std::fmt::Debug;
6059
use std::{
60+
fmt::Debug,
6161
path::{Path, PathBuf},
6262
str::FromStr,
6363
sync::Arc,
@@ -167,7 +167,7 @@ impl L1Config {
167167
}
168168

169169
pub fn create_relays(&self) -> eyre::Result<Vec<MevBoostRelay>> {
170-
let mut results = Vec::new();
170+
let mut results = Vec::with_capacity(self.relays.len());
171171
for relay in &self.relays {
172172
results.push(MevBoostRelay::from_config(relay)?);
173173
}

crates/rbuilder/src/live_builder/payload_events/payload_source.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ impl PayloadSourceMuxer {
173173
cancellation: CancellationToken,
174174
) -> Self {
175175
let (sender, receiver) = mpsc::unbounded_channel();
176-
let mut join_handles: Vec<JoinHandle<()>> = Vec::new();
176+
let mut join_handles: Vec<JoinHandle<()>> = Vec::with_capacity(cls.len());
177177
for cl in cls {
178178
let sender = sender.clone();
179179
let cancellation = cancellation.clone();

crates/rbuilder/src/live_builder/simulation/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ where
7676
current_contexts: Arc::new(Mutex::new(CurrentSimulationContexts {
7777
contexts: HashMap::default(),
7878
})),
79-
worker_threads: Vec::new(),
79+
worker_threads: Vec::with_capacity(num_workers),
8080
};
8181
for i in 0..num_workers {
8282
let ctx = Arc::clone(&result.current_contexts);

crates/rbuilder/src/primitives/order_builder.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,7 @@ impl BundleBuilder {
174174

175175
fn build(self) -> Bundle {
176176
let mut reverting_tx_hashes = Vec::new();
177-
let mut txs = Vec::new();
177+
let mut txs = Vec::with_capacity(self.txs.len());
178178
for (tx_with_blobs, opt) in self.txs {
179179
if opt {
180180
reverting_tx_hashes.push(tx_with_blobs.tx.hash);

crates/rbuilder/src/primitives/test_data_generator.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ impl TestDataGenerator {
105105
replacement_data: Option<BundleReplacementData>,
106106
) -> Bundle {
107107
let mut reverting_tx_hashes = Vec::new();
108-
let mut txs = Vec::new();
108+
let mut txs = Vec::with_capacity(txs_info.len());
109109
for tx_info in txs_info {
110110
let tx1 = self.create_tx_with_blobs_nonce(tx_info.nonce.clone());
111111
if tx_info.optional {

crates/rbuilder/src/utils/mod.rs

+5-3
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,10 @@ use alloy_primitives::{Address, Sign, I256, U256};
1818
use alloy_provider::RootProvider;
1919
use alloy_transport::BoxTransport;
2020

21-
use crate::primitives::serialize::{RawTx, TxEncoding};
22-
use crate::primitives::TransactionSignedEcRecoveredWithBlobs;
21+
use crate::primitives::{
22+
serialize::{RawTx, TxEncoding},
23+
TransactionSignedEcRecoveredWithBlobs,
24+
};
2325
use alloy_consensus::TxEnvelope;
2426
use alloy_eips::eip2718::Encodable2718;
2527
pub use noncer::{NonceCache, NonceCacheRef};
@@ -228,7 +230,7 @@ pub fn find_suggested_fee_recipient(
228230
pub fn extract_onchain_block_txs(
229231
onchain_block: &alloy_rpc_types::Block,
230232
) -> eyre::Result<Vec<TransactionSignedEcRecoveredWithBlobs>> {
231-
let mut result = Vec::new();
233+
let mut result = Vec::with_capacity(onchain_block.transactions.len());
232234
for tx in onchain_block.transactions.clone().into_transactions() {
233235
let tx_envelope: TxEnvelope = tx.try_into()?;
234236
let encoded = tx_envelope.encoded_2718();

crates/rbuilder/src/validation_api_client.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ impl Debug for ValidationError {
5454

5555
impl ValidationAPIClient {
5656
pub fn new(urls: &[&str]) -> eyre::Result<Self> {
57-
let mut providers = Vec::new();
57+
let mut providers = Vec::with_capacity(urls.len());
5858
for url in urls {
5959
providers.push(Arc::new(http_provider(url.parse()?)));
6060
}

0 commit comments

Comments
 (0)