Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Perf: avoid unnecessary allocations when transforming Expr #8591

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 14 additions & 8 deletions datafusion/expr/src/tree_node/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@

//! Tree node implementation for logical expr

use std::mem;

use crate::expr::{
AggregateFunction, AggregateFunctionDefinition, Alias, Between, BinaryExpr, Case,
Cast, GetIndexedField, GroupingSet, InList, InSubquery, Like, Placeholder,
Expand Down Expand Up @@ -378,15 +380,14 @@ impl TreeNode for Expr {
}
}

fn transform_boxed<F>(boxed_expr: Box<Expr>, transform: &mut F) -> Result<Box<Expr>>
fn transform_boxed<F>(mut boxed_expr: Box<Expr>, transform: &mut F) -> Result<Box<Expr>>
where
F: FnMut(Expr) -> Result<Expr>,
{
// TODO:
// It might be possible to avoid an allocation (the Box::new) below by reusing the box.
let expr: Expr = *boxed_expr;
let rewritten_expr = transform(expr)?;
Ok(Box::new(rewritten_expr))
// We reuse the existing Box to avoid an allocation:
let t = mem::replace(&mut *boxed_expr, Expr::Wildcard { qualifier: None });
let _ = mem::replace(&mut *boxed_expr, transform(t)?);
Ok(boxed_expr)
}

fn transform_option_box<F>(
Expand Down Expand Up @@ -417,9 +418,14 @@ where
}

/// &mut transform a `Vec` of `Expr`s
fn transform_vec<F>(v: Vec<Expr>, transform: &mut F) -> Result<Vec<Expr>>
fn transform_vec<F>(mut v: Vec<Expr>, transform: &mut F) -> Result<Vec<Expr>>
where
F: FnMut(Expr) -> Result<Expr>,
{
v.into_iter().map(transform).collect()
// Perform an in-place mutation of the Vec to avoid allocation:
for expr in v.iter_mut() {
let t = mem::replace(expr, Expr::Wildcard { qualifier: None });
let _ = mem::replace(expr, transform(t)?);
}
Ok(v)
}