This is an automated email from the ASF dual-hosted git repository.
Jefffrey pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow-rs.git
The following commit(s) were added to refs/heads/main by this push:
new 970391f248 Perf: Pre-size buffer allocations to avoid intermediate
allocations (#10262)
970391f248 is described below
commit 970391f2481be274707395ba3f7828618355da5b
Author: RIchard Baah <[email protected]>
AuthorDate: Fri Jul 10 20:26:50 2026 -0400
Perf: Pre-size buffer allocations to avoid intermediate allocations (#10262)
# Which issue does this PR close?
<!--
We generally require a GitHub issue to be filed for all bug fixes and
enhancements and this helps us generate change logs for our releases.
You can link an issue to this PR using the GitHub syntax.
-->
- last chunk of [[10125] [encode path] Minor optimizations to
arrow-flight](https://github.com/apache/arrow-rs/pull/10137)
- closes #10125
# Rationale for this change
**TLDR**: Its useful to pre-allocate vectors when you know the amount of
data it will require
When `IpcDataGenerator` uses the `IpcBodySink::Write` variant, record
batch buffer bytes are written directly into a `Vec`. If that `Vec` is
undersized, it repeatedly reallocates and copies bytes into a larger
buffer, growing exponentially (1, 4, 16, 32 ... KB ... MB) and paying
**two** costs on each reallocation:
1. an OS memory request and
2. a full copy of existing bytes into the new buffer.
For large batches this cascade is expensive, and paying it fresh on
every record batch chunk compounds the problem further. Since
`FlightDataEncoder::split_batch_for_grpc_response` splits record batches
into roughly equal-sized chunks, we exploit this by using the previous
buffer's final capacity as an estimate for the next call, keeping a
correctly-sized `Vec` alive across iterations and avoiding repeated
reallocation on the hot path.
### why not pre-allocate the buffers using an estimate with the length
`split_batch_for_grpc_response` uses?
Using the final capacity rather than the uncompressed dictionary size is
intentional, since IPC encoding and compression both affect the actual
bytes written, the final capacity naturally adapts to whatever encoding
and compression settings are in effect rather than consistently
overprovisioning.
<!--
Why are you proposing this change? If this is already explained clearly
in the issue then this section is not needed.
Explaining clearly why changes are proposed helps reviewers understand
your changes and offer better suggestions for fixes.
-->
# What changes are included in this PR?
- Move the scratch buffer out of ipc_write_context via mem::take (zero
copy)
- Write the IPC bytes into the buffer
- Record the final capacity
- Pre-allocate a fresh scratch buffer at that capacity for the next call
<!--
There is no need to duplicate the description in the issue here but it
is sometimes worth providing a summary of the individual changes in this
PR.
-->
# Are these changes tested?
n/a
<!--
We typically require tests for all PRs in order to:
1. Prevent the code from being accidentally broken by subsequent changes
2. Serve as another way to document the expected behavior of the code
If tests are not included in your PR, please explain why (for example,
are they covered by existing tests)?
If this PR claims a performance improvement, please include evidence
such as benchmark results.
-->
# Are there any user-facing changes?
no
<!--
If there are user-facing changes then we may require documentation to be
updated before approving the PR.
If there are any breaking changes to public APIs, please call them out.
-->
---------
Co-authored-by: Andrew Lamb <[email protected]>
---
arrow-flight/src/encode.rs | 35 ++++++++++++++++++-----------------
arrow-ipc/src/compression.rs | 21 +++++++++++++++++++--
arrow-ipc/src/writer.rs | 3 ++-
3 files changed, 39 insertions(+), 20 deletions(-)
diff --git a/arrow-flight/src/encode.rs b/arrow-flight/src/encode.rs
index 0b391089ae..a33b0e2d9a 100644
--- a/arrow-flight/src/encode.rs
+++ b/arrow-flight/src/encode.rs
@@ -373,7 +373,12 @@ impl FlightDataEncoder {
DictionaryHandling::Hydrate => hydrate_dictionaries(&batch,
schema)?,
};
- for batch in split_batch_for_grpc_response(batch,
self.max_flight_data_size) {
+ let batches = split_batch_for_grpc_response(batch,
self.max_flight_data_size);
+ let last = batches.len().saturating_sub(1); // handle empty batches
+ for (i, batch) in batches.into_iter().enumerate() {
+ self.encoder
+ .ipc_write_context
+ .set_reserve_scratch(i != last);
let (flight_dictionaries, flight_batch) =
self.encoder.encode_batch(&batch)?;
for dict in flight_dictionaries {
self.queue_message(dict);
@@ -666,7 +671,7 @@ fn prepare_schema_for_flight(
fn split_batch_for_grpc_response(
batch: RecordBatch,
max_flight_data_size: usize,
-) -> impl Iterator<Item = RecordBatch> {
+) -> Vec<RecordBatch> {
let size = batch
.columns()
.iter()
@@ -678,17 +683,15 @@ fn split_batch_for_grpc_response(
let num_rows = batch.num_rows();
let rows_per_batch = (num_rows / n_batches).max(1);
let mut offset = 0;
+ let mut batches = Vec::with_capacity(n_batches);
- std::iter::from_fn(move || {
- if offset < num_rows {
- let length = rows_per_batch.min(num_rows - offset);
- let slice = batch.slice(offset, length);
- offset += length;
- Some(slice)
- } else {
- None
- }
- })
+ while offset < num_rows {
+ let length = rows_per_batch.min(num_rows - offset);
+ batches.push(batch.slice(offset, length));
+ offset += length;
+ }
+
+ batches
}
/// The data needed to encode a stream of flight data, holding on to
@@ -1878,8 +1881,7 @@ mod tests {
let c = UInt32Array::from(vec![1, 2, 3, 4, 5, 6]);
let batch = RecordBatch::try_from_iter(vec![("a", Arc::new(c) as
ArrayRef)])
.expect("cannot create record batch");
- let split: Vec<_> =
- split_batch_for_grpc_response(batch.clone(),
max_flight_data_size).collect();
+ let split: Vec<_> = split_batch_for_grpc_response(batch.clone(),
max_flight_data_size);
assert_eq!(split.len(), 1);
assert_eq!(batch, split[0]);
@@ -1889,8 +1891,7 @@ mod tests {
let c = UInt8Array::from((0..n_rows).map(|i| (i % 256) as
u8).collect::<Vec<_>>());
let batch = RecordBatch::try_from_iter(vec![("a", Arc::new(c) as
ArrayRef)])
.expect("cannot create record batch");
- let split: Vec<_> =
- split_batch_for_grpc_response(batch.clone(),
max_flight_data_size).collect();
+ let split: Vec<_> = split_batch_for_grpc_response(batch.clone(),
max_flight_data_size);
assert_eq!(split.len(), 3);
assert_eq!(
split.iter().map(|batch| batch.num_rows()).sum::<usize>(),
@@ -1935,7 +1936,7 @@ mod tests {
let input_rows = batch.num_rows();
let split: Vec<_> =
- split_batch_for_grpc_response(batch.clone(),
max_flight_data_size_bytes).collect();
+ split_batch_for_grpc_response(batch.clone(),
max_flight_data_size_bytes);
let sizes: Vec<_> = split.iter().map(RecordBatch::num_rows).collect();
let output_rows: usize = sizes.iter().sum();
diff --git a/arrow-ipc/src/compression.rs b/arrow-ipc/src/compression.rs
index 79879332d4..311892877b 100644
--- a/arrow-ipc/src/compression.rs
+++ b/arrow-ipc/src/compression.rs
@@ -31,8 +31,8 @@ const DEFAULT_ZSTD_COMPRESSION_LEVEL: i32 = 3;
/// compression. Also holds a [`FlatBufferBuilder`] that is reused across IPC
writes.
#[derive(Default)]
pub struct IpcWriteContext {
- #[expect(dead_code)]
- pub(crate) scratch: Vec<u8>,
+ scratch: Vec<u8>,
+ reserve_scratch: bool,
fbb: FlatBufferBuilder<'static>,
#[cfg(feature = "zstd")]
compressor: Option<zstd::bulk::Compressor<'static>>,
@@ -44,6 +44,23 @@ impl IpcWriteContext {
&mut self.fbb
}
+ /// Set whether the scratch buffer capacity should be reserved after each
encode for reuse
+ /// on the next call. Set to `false` for the final batch in a sequence to
avoid a
+ /// pointless allocation. by default, this is set to `false`.
+ pub fn set_reserve_scratch(&mut self, reserve: bool) {
+ self.reserve_scratch = reserve;
+ }
+ /// Reserve the scratch buffer capacity for reuse on the next call. This
is a no-op if
+ /// `reserve_scratch` is set to `false`.
+ pub(crate) fn reserve_scratch_with_capacity(&mut self, additional: usize) {
+ if self.reserve_scratch {
+ self.scratch.reserve(additional);
+ }
+ }
+ pub(crate) fn scratch(&mut self) -> Vec<u8> {
+ std::mem::take(&mut self.scratch)
+ }
+
#[cfg(feature = "zstd")]
fn zstd_compressor(&mut self, level: i32) -> &mut
zstd::bulk::Compressor<'static> {
self.compressor.get_or_insert_with(|| {
diff --git a/arrow-ipc/src/writer.rs b/arrow-ipc/src/writer.rs
index 8e0ca81bf1..311cb44e46 100644
--- a/arrow-ipc/src/writer.rs
+++ b/arrow-ipc/src/writer.rs
@@ -622,7 +622,7 @@ impl IpcDataGenerator {
) -> Result<(Vec<EncodedData>, EncodedData), ArrowError> {
let encoded_dictionaries =
self.encode_all_dicts(batch, dictionary_tracker, write_options,
ipc_write_context)?;
- let mut arrow_data = Vec::new();
+ let mut arrow_data = ipc_write_context.scratch();
let (ipc_message, _, tail_pad) = self.record_batch_to_bytes(
batch,
write_options,
@@ -630,6 +630,7 @@ impl IpcDataGenerator {
&mut IpcBodySink::Write(&mut arrow_data),
)?;
arrow_data.extend_from_slice(&PADDING[..tail_pad]);
+ ipc_write_context.reserve_scratch_with_capacity(arrow_data.capacity());
Ok((
encoded_dictionaries,
EncodedData {