Skip to content

Commit 43567b4

Browse files
authored
perf: improve performance of levenshtein by reusing cache buffer (#19532)
## 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. For example `Closes #123` indicates that this PR will close issue #123. --> - Closes #. ## Rationale for this change <!-- 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? <!-- 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. --> Add levenshtein_with_buffer() function that accepts a reusable cache buffer to avoid allocating a new Vec<usize> for each distance calculation. Changes: - Added levenshtein_with_buffer() in datafusion-common that takes a mutable Vec<usize> buffer parameter - Updated levenshtein function to use the optimized version with a reusable buffer across all rows - Added benchmark to measure performance improvements Optimization: - Before: Allocated new Vec<usize> cache for every row - After: Single Vec<usize> buffer reused across all rows Benchmark Results: - size=1024, str_len=8: 60.6 µs → 45.9 µs (24% faster) - size=1024, str_len=32: 615.5 µs → 598.5 µs (3% faster) - size=4096, str_len=8: 234.7 µs → 180.5 µs (23% faster) - size=4096, str_len=32: 2.46 ms → 2.38 ms (3% faster) The optimization shows significant improvements for shorter strings (23-24%) where allocation overhead is more prominent relative to algorithm cost. For longer strings, the O(m×n) algorithm complexity dominates, but still shows measurable 3% improvement from eliminating per-row allocations. ## Are these changes tested? <!-- 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)? --> ## Are there any user-facing changes? <!-- 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 add the `api change` label. -->
1 parent 94709dc commit 43567b4

File tree

4 files changed

+146
-6
lines changed

4 files changed

+146
-6
lines changed

datafusion/common/src/utils/mod.rs

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -693,10 +693,14 @@ pub mod datafusion_strsim {
693693
}
694694

695695
/// Calculates the minimum number of insertions, deletions, and substitutions
696-
/// required to change one sequence into the other.
697-
fn generic_levenshtein<'a, 'b, Iter1, Iter2, Elem1, Elem2>(
696+
/// required to change one sequence into the other, using a reusable cache buffer.
697+
///
698+
/// This is the generic implementation that works with any iterator types.
699+
/// The `cache` buffer will be resized as needed and reused across calls.
700+
fn generic_levenshtein_with_buffer<'a, 'b, Iter1, Iter2, Elem1, Elem2>(
698701
a: &'a Iter1,
699702
b: &'b Iter2,
703+
cache: &mut Vec<usize>,
700704
) -> usize
701705
where
702706
&'a Iter1: IntoIterator<Item = Elem1>,
@@ -709,7 +713,9 @@ pub mod datafusion_strsim {
709713
return b_len;
710714
}
711715

712-
let mut cache: Vec<usize> = (1..b_len + 1).collect();
716+
// Resize cache to fit b_len elements
717+
cache.clear();
718+
cache.extend(1..=b_len);
713719

714720
let mut result = 0;
715721

@@ -729,6 +735,21 @@ pub mod datafusion_strsim {
729735
result
730736
}
731737

738+
/// Calculates the minimum number of insertions, deletions, and substitutions
739+
/// required to change one sequence into the other.
740+
fn generic_levenshtein<'a, 'b, Iter1, Iter2, Elem1, Elem2>(
741+
a: &'a Iter1,
742+
b: &'b Iter2,
743+
) -> usize
744+
where
745+
&'a Iter1: IntoIterator<Item = Elem1>,
746+
&'b Iter2: IntoIterator<Item = Elem2>,
747+
Elem1: PartialEq<Elem2>,
748+
{
749+
let mut cache = Vec::new();
750+
generic_levenshtein_with_buffer(a, b, &mut cache)
751+
}
752+
732753
/// Calculates the minimum number of insertions, deletions, and substitutions
733754
/// required to change one string into the other.
734755
///
@@ -741,6 +762,15 @@ pub mod datafusion_strsim {
741762
generic_levenshtein(&StringWrapper(a), &StringWrapper(b))
742763
}
743764

765+
/// Calculates the Levenshtein distance using a reusable cache buffer.
766+
/// This avoids allocating a new Vec for each call, improving performance
767+
/// when computing many distances.
768+
///
769+
/// The `cache` buffer will be resized as needed and reused across calls.
770+
pub fn levenshtein_with_buffer(a: &str, b: &str, cache: &mut Vec<usize>) -> usize {
771+
generic_levenshtein_with_buffer(&StringWrapper(a), &StringWrapper(b), cache)
772+
}
773+
744774
/// Calculates the normalized Levenshtein distance between two strings.
745775
/// The normalized distance is a value between 0.0 and 1.0, where 1.0 indicates
746776
/// that the strings are identical and 0.0 indicates no similarity.

datafusion/functions/Cargo.toml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -269,3 +269,8 @@ required-features = ["string_expressions"]
269269
harness = false
270270
name = "ends_with"
271271
required-features = ["string_expressions"]
272+
273+
[[bench]]
274+
harness = false
275+
name = "levenshtein"
276+
required-features = ["unicode_expressions"]
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
// Licensed to the Apache Software Foundation (ASF) under one
2+
// or more contributor license agreements. See the NOTICE file
3+
// distributed with this work for additional information
4+
// regarding copyright ownership. The ASF licenses this file
5+
// to you under the Apache License, Version 2.0 (the
6+
// "License"); you may not use this file except in compliance
7+
// with the License. You may obtain a copy of the License at
8+
//
9+
// http://www.apache.org/licenses/LICENSE-2.0
10+
//
11+
// Unless required by applicable law or agreed to in writing,
12+
// software distributed under the License is distributed on an
13+
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
// KIND, either express or implied. See the License for the
15+
// specific language governing permissions and limitations
16+
// under the License.
17+
18+
extern crate criterion;
19+
20+
use arrow::array::OffsetSizeTrait;
21+
use arrow::datatypes::{DataType, Field};
22+
use arrow::util::bench_util::create_string_array_with_len;
23+
use criterion::{Criterion, SamplingMode, criterion_group, criterion_main};
24+
use datafusion_common::DataFusionError;
25+
use datafusion_common::config::ConfigOptions;
26+
use datafusion_expr::{ColumnarValue, ScalarFunctionArgs};
27+
use datafusion_functions::string;
28+
use std::hint::black_box;
29+
use std::sync::Arc;
30+
use std::time::Duration;
31+
32+
fn create_args<O: OffsetSizeTrait>(size: usize, str_len: usize) -> Vec<ColumnarValue> {
33+
let string1_array = Arc::new(create_string_array_with_len::<O>(size, 0.1, str_len));
34+
let string2_array = Arc::new(create_string_array_with_len::<O>(size, 0.1, str_len));
35+
36+
vec![
37+
ColumnarValue::Array(string1_array),
38+
ColumnarValue::Array(string2_array),
39+
]
40+
}
41+
42+
fn invoke_levenshtein_with_args(
43+
args: Vec<ColumnarValue>,
44+
number_rows: usize,
45+
) -> Result<ColumnarValue, DataFusionError> {
46+
let arg_fields = args
47+
.iter()
48+
.enumerate()
49+
.map(|(idx, arg)| Field::new(format!("arg_{idx}"), arg.data_type(), true).into())
50+
.collect::<Vec<_>>();
51+
let config_options = Arc::new(ConfigOptions::default());
52+
53+
string::levenshtein().invoke_with_args(ScalarFunctionArgs {
54+
args,
55+
arg_fields,
56+
number_rows,
57+
return_field: Field::new("f", DataType::Int32, true).into(),
58+
config_options: Arc::clone(&config_options),
59+
})
60+
}
61+
62+
fn criterion_benchmark(c: &mut Criterion) {
63+
for size in [1024, 4096] {
64+
let mut group = c.benchmark_group(format!("levenshtein size={size}"));
65+
group.sampling_mode(SamplingMode::Flat);
66+
group.sample_size(10);
67+
group.measurement_time(Duration::from_secs(10));
68+
69+
for str_len in [8, 32] {
70+
let args = create_args::<i32>(size, str_len);
71+
group.bench_function(
72+
format!("levenshtein_string [size={size}, str_len={str_len}]"),
73+
|b| {
74+
b.iter(|| {
75+
let args_cloned = args.clone();
76+
black_box(invoke_levenshtein_with_args(args_cloned, size))
77+
})
78+
},
79+
);
80+
}
81+
82+
group.finish();
83+
}
84+
}
85+
86+
criterion_group!(benches, criterion_benchmark);
87+
criterion_main!(benches);

datafusion/functions/src/string/levenshtein.rs

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -151,12 +151,18 @@ fn levenshtein<T: OffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef> {
151151
DataType::Utf8View => {
152152
let str1_array = as_string_view_array(&str1)?;
153153
let str2_array = as_string_view_array(&str2)?;
154+
155+
// Reusable buffer to avoid allocating for each row
156+
let mut cache = Vec::new();
157+
154158
let result = str1_array
155159
.iter()
156160
.zip(str2_array.iter())
157161
.map(|(string1, string2)| match (string1, string2) {
158162
(Some(string1), Some(string2)) => {
159-
Some(datafusion_strsim::levenshtein(string1, string2) as i32)
163+
Some(datafusion_strsim::levenshtein_with_buffer(
164+
string1, string2, &mut cache,
165+
) as i32)
160166
}
161167
_ => None,
162168
})
@@ -166,12 +172,18 @@ fn levenshtein<T: OffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef> {
166172
DataType::Utf8 => {
167173
let str1_array = as_generic_string_array::<T>(&str1)?;
168174
let str2_array = as_generic_string_array::<T>(&str2)?;
175+
176+
// Reusable buffer to avoid allocating for each row
177+
let mut cache = Vec::new();
178+
169179
let result = str1_array
170180
.iter()
171181
.zip(str2_array.iter())
172182
.map(|(string1, string2)| match (string1, string2) {
173183
(Some(string1), Some(string2)) => {
174-
Some(datafusion_strsim::levenshtein(string1, string2) as i32)
184+
Some(datafusion_strsim::levenshtein_with_buffer(
185+
string1, string2, &mut cache,
186+
) as i32)
175187
}
176188
_ => None,
177189
})
@@ -181,12 +193,18 @@ fn levenshtein<T: OffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef> {
181193
DataType::LargeUtf8 => {
182194
let str1_array = as_generic_string_array::<T>(&str1)?;
183195
let str2_array = as_generic_string_array::<T>(&str2)?;
196+
197+
// Reusable buffer to avoid allocating for each row
198+
let mut cache = Vec::new();
199+
184200
let result = str1_array
185201
.iter()
186202
.zip(str2_array.iter())
187203
.map(|(string1, string2)| match (string1, string2) {
188204
(Some(string1), Some(string2)) => {
189-
Some(datafusion_strsim::levenshtein(string1, string2) as i64)
205+
Some(datafusion_strsim::levenshtein_with_buffer(
206+
string1, string2, &mut cache,
207+
) as i64)
190208
}
191209
_ => None,
192210
})

0 commit comments

Comments
 (0)