Skip to content

Commit e5ca510

Browse files
authored
perf: Improve performance of to_hex (> 2x) (#19503)
## 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. --> N/A ## 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. --> | Benchmark | Original (main) | After reusable buffer | After no-builder | Total Improvement | |------------------|-----------------|-----------------------|------------------|-------------------| | size=1024 | | | | | | i32_random | 15.53 µs | 7.32 µs | 6.41 µs | -58.7% | | i64_random | 16.37 µs | 8.01 µs | 6.92 µs | -57.7% | | i64_large_values | 15.65 µs | 8.34 µs | 7.06 µs | -54.9% | | size=4096 | | | | | | i32_random | 57.11 µs | 28.39 µs | 24.66 µs | -56.8% | | i64_random | 62.19 µs | 31.10 µs | 27.62 µs | -55.6% | | i64_large_values | 61.10 µs | 30.60 µs | 26.98 µs | -55.8% | | size=8192 | | | | | | i32_random | 118.71 µs | 67.62 µs | 51.45 µs | -56.7% | | i64_random | 141.29 µs | 62.20 µs | 54.19 µs | -61.6% | | i64_large_values | 123.05 µs | 60.14 µs | 53.45 µs | -56.6% | ## 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. --> Avoid string allocations and re-use a mutable buffer. ## 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 ae35177 commit e5ca510

File tree

2 files changed

+207
-61
lines changed

2 files changed

+207
-61
lines changed

datafusion/functions/benches/to_hex.rs

Lines changed: 83 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -17,56 +17,102 @@
1717

1818
extern crate criterion;
1919

20+
use arrow::array::Int64Array;
2021
use arrow::datatypes::{DataType, Field, Int32Type, Int64Type};
2122
use arrow::util::bench_util::create_primitive_array;
22-
use criterion::{Criterion, criterion_group, criterion_main};
23+
use criterion::{Criterion, SamplingMode, criterion_group, criterion_main};
2324
use datafusion_common::config::ConfigOptions;
2425
use datafusion_expr::{ColumnarValue, ScalarFunctionArgs};
2526
use datafusion_functions::string;
2627
use std::hint::black_box;
2728
use std::sync::Arc;
29+
use std::time::Duration;
2830

2931
fn criterion_benchmark(c: &mut Criterion) {
3032
let hex = string::to_hex();
31-
let size = 1024;
32-
let i32_array = Arc::new(create_primitive_array::<Int32Type>(size, 0.2));
33-
let batch_len = i32_array.len();
34-
let i32_args = vec![ColumnarValue::Array(i32_array)];
3533
let config_options = Arc::new(ConfigOptions::default());
3634

37-
c.bench_function(&format!("to_hex i32 array: {size}"), |b| {
38-
b.iter(|| {
39-
let args_cloned = i32_args.clone();
40-
black_box(
41-
hex.invoke_with_args(ScalarFunctionArgs {
42-
args: args_cloned,
43-
arg_fields: vec![Field::new("a", DataType::Int32, false).into()],
44-
number_rows: batch_len,
45-
return_field: Field::new("f", DataType::Utf8, true).into(),
46-
config_options: Arc::clone(&config_options),
47-
})
48-
.unwrap(),
49-
)
50-
})
51-
});
52-
let i64_array = Arc::new(create_primitive_array::<Int64Type>(size, 0.2));
53-
let batch_len = i64_array.len();
54-
let i64_args = vec![ColumnarValue::Array(i64_array)];
55-
c.bench_function(&format!("to_hex i64 array: {size}"), |b| {
56-
b.iter(|| {
57-
let args_cloned = i64_args.clone();
58-
black_box(
59-
hex.invoke_with_args(ScalarFunctionArgs {
60-
args: args_cloned,
61-
arg_fields: vec![Field::new("a", DataType::Int64, false).into()],
62-
number_rows: batch_len,
63-
return_field: Field::new("f", DataType::Utf8, true).into(),
64-
config_options: Arc::clone(&config_options),
35+
for size in [1024, 4096, 8192] {
36+
let mut group = c.benchmark_group(format!("to_hex size={size}"));
37+
group.sampling_mode(SamplingMode::Flat);
38+
group.sample_size(10);
39+
group.measurement_time(Duration::from_secs(10));
40+
41+
// i32 array with random values
42+
let i32_array = Arc::new(create_primitive_array::<Int32Type>(size, 0.1));
43+
let batch_len = i32_array.len();
44+
let i32_args = vec![ColumnarValue::Array(i32_array)];
45+
46+
group.bench_function("i32_random", |b| {
47+
b.iter(|| {
48+
let args_cloned = i32_args.clone();
49+
black_box(
50+
hex.invoke_with_args(ScalarFunctionArgs {
51+
args: args_cloned,
52+
arg_fields: vec![Field::new("a", DataType::Int32, true).into()],
53+
number_rows: batch_len,
54+
return_field: Field::new("f", DataType::Utf8, true).into(),
55+
config_options: Arc::clone(&config_options),
56+
})
57+
.unwrap(),
58+
)
59+
})
60+
});
61+
62+
// i64 array with random values (produces longer hex strings)
63+
let i64_array = Arc::new(create_primitive_array::<Int64Type>(size, 0.1));
64+
let batch_len = i64_array.len();
65+
let i64_args = vec![ColumnarValue::Array(i64_array)];
66+
67+
group.bench_function("i64_random", |b| {
68+
b.iter(|| {
69+
let args_cloned = i64_args.clone();
70+
black_box(
71+
hex.invoke_with_args(ScalarFunctionArgs {
72+
args: args_cloned,
73+
arg_fields: vec![Field::new("a", DataType::Int64, true).into()],
74+
number_rows: batch_len,
75+
return_field: Field::new("f", DataType::Utf8, true).into(),
76+
config_options: Arc::clone(&config_options),
77+
})
78+
.unwrap(),
79+
)
80+
})
81+
});
82+
83+
// i64 array with large values (max length hex strings)
84+
let i64_large_array = Arc::new(Int64Array::from(
85+
(0..size)
86+
.map(|i| {
87+
if i % 10 == 0 {
88+
None
89+
} else {
90+
Some(i64::MAX - i as i64)
91+
}
6592
})
66-
.unwrap(),
67-
)
68-
})
69-
});
93+
.collect::<Vec<_>>(),
94+
));
95+
let batch_len = i64_large_array.len();
96+
let i64_large_args = vec![ColumnarValue::Array(i64_large_array)];
97+
98+
group.bench_function("i64_large_values", |b| {
99+
b.iter(|| {
100+
let args_cloned = i64_large_args.clone();
101+
black_box(
102+
hex.invoke_with_args(ScalarFunctionArgs {
103+
args: args_cloned,
104+
arg_fields: vec![Field::new("a", DataType::Int64, true).into()],
105+
number_rows: batch_len,
106+
return_field: Field::new("f", DataType::Utf8, true).into(),
107+
config_options: Arc::clone(&config_options),
108+
})
109+
.unwrap(),
110+
)
111+
})
112+
});
113+
114+
group.finish();
115+
}
70116
}
71117

72118
criterion_group!(benches, criterion_benchmark);

datafusion/functions/src/string/to_hex.rs

Lines changed: 124 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,11 @@
1616
// under the License.
1717

1818
use std::any::Any;
19-
use std::fmt::Write;
2019
use std::sync::Arc;
2120

2221
use crate::utils::make_scalar_function;
23-
use arrow::array::{ArrayRef, GenericStringBuilder};
22+
use arrow::array::{Array, ArrayRef, StringArray};
23+
use arrow::buffer::{Buffer, OffsetBuffer};
2424
use arrow::datatypes::DataType::{
2525
Int8, Int16, Int32, Int64, UInt8, UInt16, UInt32, UInt64, Utf8,
2626
};
@@ -37,42 +37,142 @@ use datafusion_expr::{ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility};
3737
use datafusion_expr_common::signature::TypeSignature::Exact;
3838
use datafusion_macros::user_doc;
3939

40+
/// Hex lookup table for fast conversion
41+
const HEX_CHARS: &[u8; 16] = b"0123456789abcdef";
42+
4043
/// Converts the number to its equivalent hexadecimal representation.
4144
/// to_hex(2147483647) = '7fffffff'
4245
fn to_hex<T: ArrowPrimitiveType>(args: &[ArrayRef]) -> Result<ArrayRef>
4346
where
44-
T::Native: std::fmt::LowerHex,
47+
T::Native: ToHex,
4548
{
4649
let integer_array = as_primitive_array::<T>(&args[0])?;
50+
let len = integer_array.len();
4751

48-
let mut result = GenericStringBuilder::<i32>::with_capacity(
49-
integer_array.len(),
50-
// * 8 to convert to bits, / 4 bits per hex char
51-
integer_array.len() * (T::Native::get_byte_width() * 8 / 4),
52-
);
52+
// Max hex string length: 16 chars for u64/i64
53+
let max_hex_len = T::Native::get_byte_width() * 2;
5354

54-
for integer in integer_array {
55-
if let Some(value) = integer {
56-
if let Some(value_usize) = value.to_usize() {
57-
write!(result, "{value_usize:x}")?;
58-
} else if let Some(value_isize) = value.to_isize() {
59-
write!(result, "{value_isize:x}")?;
60-
} else {
61-
return exec_err!(
62-
"Unsupported data type {integer:?} for function to_hex"
63-
);
64-
}
65-
result.append_value("");
66-
} else {
67-
result.append_null();
68-
}
55+
// Pre-allocate buffers - avoid the builder API overhead
56+
let mut offsets: Vec<i32> = Vec::with_capacity(len + 1);
57+
let mut values: Vec<u8> = Vec::with_capacity(len * max_hex_len);
58+
59+
// Reusable buffer for hex conversion
60+
let mut hex_buffer = [0u8; 16];
61+
62+
// Start with offset 0
63+
offsets.push(0);
64+
65+
// Process all values directly (including null slots - we write empty strings for nulls)
66+
// The null bitmap will mark which entries are actually null
67+
for value in integer_array.values() {
68+
let hex_len = value.write_hex_to_buffer(&mut hex_buffer);
69+
values.extend_from_slice(&hex_buffer[16 - hex_len..]);
70+
offsets.push(values.len() as i32);
6971
}
7072

71-
let result = result.finish();
73+
// Copy null bitmap from input (nulls pass through unchanged)
74+
let nulls = integer_array.nulls().cloned();
75+
76+
// SAFETY: offsets are valid (monotonically increasing, last value equals values.len())
77+
// and values contains valid UTF-8 (only ASCII hex digits)
78+
let offsets =
79+
unsafe { OffsetBuffer::new_unchecked(Buffer::from_vec(offsets).into()) };
80+
let result = StringArray::new(offsets, Buffer::from_vec(values), nulls);
7281

7382
Ok(Arc::new(result) as ArrayRef)
7483
}
7584

85+
/// Trait for converting integer types to hexadecimal in a buffer
86+
trait ToHex: ArrowNativeType {
87+
/// Write hex representation to buffer and return the number of hex digits written.
88+
/// The hex digits are written right-aligned in the buffer (starting from position 16 - len).
89+
fn write_hex_to_buffer(self, buffer: &mut [u8; 16]) -> usize;
90+
}
91+
92+
/// Write unsigned value to hex buffer and return the number of digits written.
93+
/// Digits are written right-aligned in the buffer.
94+
#[inline]
95+
fn write_unsigned_hex_to_buffer(value: u64, buffer: &mut [u8; 16]) -> usize {
96+
if value == 0 {
97+
buffer[15] = b'0';
98+
return 1;
99+
}
100+
101+
// Write hex digits from right to left
102+
let mut pos = 16;
103+
let mut v = value;
104+
while v > 0 {
105+
pos -= 1;
106+
buffer[pos] = HEX_CHARS[(v & 0xf) as usize];
107+
v >>= 4;
108+
}
109+
110+
16 - pos
111+
}
112+
113+
/// Write signed value to hex buffer (two's complement for negative) and return digit count
114+
#[inline]
115+
fn write_signed_hex_to_buffer(value: i64, buffer: &mut [u8; 16]) -> usize {
116+
// For negative values, use two's complement representation (same as casting to u64)
117+
write_unsigned_hex_to_buffer(value as u64, buffer)
118+
}
119+
120+
impl ToHex for i8 {
121+
#[inline]
122+
fn write_hex_to_buffer(self, buffer: &mut [u8; 16]) -> usize {
123+
write_signed_hex_to_buffer(self as i64, buffer)
124+
}
125+
}
126+
127+
impl ToHex for i16 {
128+
#[inline]
129+
fn write_hex_to_buffer(self, buffer: &mut [u8; 16]) -> usize {
130+
write_signed_hex_to_buffer(self as i64, buffer)
131+
}
132+
}
133+
134+
impl ToHex for i32 {
135+
#[inline]
136+
fn write_hex_to_buffer(self, buffer: &mut [u8; 16]) -> usize {
137+
write_signed_hex_to_buffer(self as i64, buffer)
138+
}
139+
}
140+
141+
impl ToHex for i64 {
142+
#[inline]
143+
fn write_hex_to_buffer(self, buffer: &mut [u8; 16]) -> usize {
144+
write_signed_hex_to_buffer(self, buffer)
145+
}
146+
}
147+
148+
impl ToHex for u8 {
149+
#[inline]
150+
fn write_hex_to_buffer(self, buffer: &mut [u8; 16]) -> usize {
151+
write_unsigned_hex_to_buffer(self as u64, buffer)
152+
}
153+
}
154+
155+
impl ToHex for u16 {
156+
#[inline]
157+
fn write_hex_to_buffer(self, buffer: &mut [u8; 16]) -> usize {
158+
write_unsigned_hex_to_buffer(self as u64, buffer)
159+
}
160+
}
161+
162+
impl ToHex for u32 {
163+
#[inline]
164+
fn write_hex_to_buffer(self, buffer: &mut [u8; 16]) -> usize {
165+
write_unsigned_hex_to_buffer(self as u64, buffer)
166+
}
167+
}
168+
169+
impl ToHex for u64 {
170+
#[inline]
171+
fn write_hex_to_buffer(self, buffer: &mut [u8; 16]) -> usize {
172+
write_unsigned_hex_to_buffer(self, buffer)
173+
}
174+
}
175+
76176
#[user_doc(
77177
doc_section(label = "String Functions"),
78178
description = "Converts an integer to a hexadecimal string.",

0 commit comments

Comments
 (0)